c++ - 查找用户输入值的总和

标签 c++

我需要帮助使用 C++ 将多个用户输入的值相加

double total;     // Accumulates total
double price;      // Gets next price from user
int numItems;     // Number of items
int counter = 1;  // Loop control counter

cout << "How many items do you have? ";
cin >> numItems;
cout << endl;

while (counter <= numItems) {
    total = 0;
    cout << "Enter the price of item " << counter << ": ";
    cin >> price;
    cout << endl;
    total += price;
    counter++;
}
cout << "The total price is: " << total << endl;

当我运行我的代码时,我最终只从用户那里得到一个值的总和

最佳答案

是的,正如 Chetan Ranpariya 所说:

total = 0; 应该在 while 循环之前。

关于c++ - 查找用户输入值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58194131/

相关文章:

c++ - cin.getline() 正在删除我在 C++ 中输入的第一个让步

c++ - 与 gcc 静态链接时为 "Undefined reference to dlopen"

c++ - 使用 getline 读取文件/输入时出现段错误

c++ - 在 Win32 中从字符串中解析日期

c++ - 重载二维数组运算符并抛出异常

javascript - JavaScript 函数中的参数和临时变量

c++ - C++ 中用于维护插入顺序并消除重复的数据结构

c++ - 禁止在类内使用方法

c++ - 如何删除 vector 中的重复项(不排序)C++

C++ 流 : Insert string after newline