c++ - 如何在 C++ 中使用带有 'do while' 循环的计数器?

标签 c++ visual-studio do-while

我试图让这个“do while”循环运行 3 次,然后在“do while”循环内的 while 循环中显示累加器中包含的数量。

它似乎计数正确,但只在第一次运行 while 循环。运行时,它不会继续询问下一组数字,而是只显示第一批(正确加起来)。我试过切换一些代码并搜索谷歌,但找不到答案。

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int storeNum = 1;
    int payRollAmount = 0;
    int totalPayroll = 0;

    do
    {
        cout << "Store " << storeNum << ":" << endl;

        while (payRollAmount <= -1)
        {
            cout << "Enter Store's Payroll Amount (-1 to exit): ";
            cin >> payRollAmount;

            totalPayroll += payRollAmount;
        }

        storeNum++;
    } while (storeNum <= 3);

    cout << "The Total Payroll is: " << totalPayroll << endl;

    system("pause");
    return 0;
}

The code should take in an unknown amount of "payrolls," allow you to exit using -1, and then continue on to the next stores payrolls. It should do this 3 times, and then display the total amount (all numbers entered added together.

最佳答案

您好,也许在每次迭代时重置 payRollAmount?这样它将继续请求输入。

for (int amount = 0; amount != -1; ) {
    cout << "Enter Store's Payroll Amount (-1 to exit): ";
    cin >> amount;
    totalPayroll += amount;
}

关于c++ - 如何在 C++ 中使用带有 'do while' 循环的计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55961005/

相关文章:

python - 在 C++ 中初始化非常大的 vector

c++ - 一个类可以继承自另一个具体化的类模板吗?

visual-studio - Visual Studio 中代码重构(var 重命名)的键盘快捷键

Java: do-while(regex), hashtable.containsKey() 可能吗?

c# - 在 C# 中执行 .. While 循环?

c++ - 如何在派生类中初始化静态成员?

c++ - 引用和指针都存储地址?

visual-studio - Visual Studio 2005 : is there a compiler option to initialize all stack-based variables to zero?

c# - 使用VS2019创建WebService

c++ - 如何让 cin 停止跳过?