c++ - 循环时对用户输入的值求和 (C++)

标签 c++

我正在尝试编写一个程序,在该程序中将提示用户输入整数 3 次。在每个整数之后,输入后将显示一个总和。然后,对于第二个和第三个整数,应将这些数字添加到循环中的初始总和上。这是我所做的:

#include <iostream>
using namespace std;
int main () {

double number=0, total=0;


    for (double n=0; n<3; n++){
   cout << "Enter an integer: ";
   cin >> number;

   cout << "Sum is: " << number <<endl;
   total+=number; }

}

这是目前的输出:

Enter an integer: 2                                                                                 
Sum is: 2                                                                                           
Enter an integer: 3                                                                                 
Sum is: 3                                                                                           
Enter an integer: 4                                                                                 
Sum is: 4 

目标是让整数继续添加到总和中,直到循环完成。这是我想要实现的输出:

Enter an integer: 2                                                                                 
Sum is: 2                                                                                           
Enter an integer: 3                                                                                 
Sum is: 5                                                                                           
Enter an integer: 4                                                                                 
Sum is: 9 

任何帮助将不胜感激,因为我对如何解决这部分感到困惑,这是我需要弄清楚才能完成的唯一部分。感谢您花时间阅读本文!

最佳答案

cout << "Sum is: " << number << endl;

在这一行中,您打印的是当前数字,而不是总数。您需要改用 total

同时将 total += number; 移到上一行之前。否则显示时会落后一步。

因此你的代码应该是这样的:

#include <iostream>
using namespace std;

int main () {
  double number=0, total=0;
  for (double n=0; n<3; n++){
    cout << "Enter an integer: ";
    cin >> number;
    total+=number; 
    cout << "Sum is: " << total << endl;
  }
}

关于c++ - 循环时对用户输入的值求和 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55485832/

相关文章:

c++ - 已在 *.obj 中定义

c++ - 将 void* 转换为 std::function<void()>

c++ - 无论是在 C++ 还是 C 中,相同的数字代码都会返回不同的输出

c++ - 克服 CUDA 中的复制开销

c++ - Boost spirit 解析器属性类型不起作用。

c++ - LNK2001 : unresolved external symbol threadIdx

c++ - 使用什么数据结构来存储游戏对象的基于 2D 单元的 map ?

c++ - 强制 QLineEdit 成为 double 值的集合

c++ - CMake Exported Lib - 在客户端应用程序中找不到包含/lib 路径

c++ - 删除指向小部件 Qt C++ 的指针