首页 > 解决方案 > 试图结束 for 循环

问题描述

我正在尝试创建一个循环,允许用户在数组中输入任意数量的元素,然后对这些元素求和。当用户输入负数时,我需要终止循环。我将如何终止这个?

double sum = 0;
double group[] = { 0 };

for (int i = 0; i >= 0; i++) {

    cout << "Please enter employee salary. Enter negative number to end." << endl;
    cout << "Employee " << i + 1 << ": $";
    cin >> group[i];
    if (i < 0) {
        break;
    }
    sum += group[i];
}
cout << "The total salary ouput for Ernest Inc is: $" << fixed << showpoint << setprecision(2) << sum << endl;

标签: c++

解决方案


当用户输入负数时,我需要终止循环。

为此,while循环会比for. 您还应该使用vectorwhich 允许任意数量的项目。

像这样的东西:

    vector<double> group;
    double salary;
    while (true)
    {
        
        cout << "Please enter employee salary. Enter negative number to end." << endl;
        cout << "Employee " << i + 1 << ": $";
        cin >> salary;
        if (salary<0)
        {
            break;
        }
        group.push_back(salary);
        sum += salary;
    }

推荐阅读