在for循环中仅显示系列fum的最后结果

时间:2018-04-30 21:06:09

标签: c++ for-loop if-statement sum

我正在编写一个代码来汇总一系列数字,但它会继续显示所有结果。我只需要最后一个数字总和

的结果

我的代码:

//Sum of numbrs which are divisible by either 3 or 5
cout << "\nSum of numbers: ";

for ( numbers = 1; numbers <= limit; numbers++ )
{
    if ( ( numbers%3 == 0 ) || ( numbers%5 == 0 ) )
    {
        if (  !( numbers%3 == 0 && numbers%5 == 0 )  )
        {
            sum += numbers; 
            cout << sum << " ";
        }
    }
}

输出:

Sum of numbers: 3 8 14 23 33 45 63 83 104

我在上面的例子中只需要最后一个值为104.

1 个答案:

答案 0 :(得分:2)

cout << sum << " ";移至for循环之外。毕竟,在我们完成计算之前,我们如何打印总和?

即:

for ( numbers = 1; numbers <= limit; numbers++ )
{
    ...
}

cout << sum << " ";