我正在编写一个代码来汇总一系列数字,但它会继续显示所有结果。我只需要最后一个数字总和
的结果我的代码:
//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.
答案 0 :(得分:2)
将cout << sum << " ";
移至for循环之外。毕竟,在我们完成计算之前,我们如何打印总和?
即:
for ( numbers = 1; numbers <= limit; numbers++ )
{
...
}
cout << sum << " ";