c++ - 试图结束 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;
解决方案
当用户输入负数时,我需要终止循环。
为此,while
循环会比for
. 您还应该使用vector
which 允许任意数量的项目。
像这样的东西:
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;
}
推荐阅读
- angular - 在 WCF Rest 服务和 .Net WebAPI 之间进行通信时,无法在 WCF 方法中获取正确的对象
- typescript - 无法确定名为参数的 GraphQL 输入类型
- sql - 有没有办法在 SQL Server Management Studio (SSMS) 中分离查询结果?
- react-native - 滚动到 FlatList 中的特定项目
- llvm - 无法使用 afl-clang-fast++ 交叉编译和链接源代码
- dependencies - 为什么不在php di注入容器函数中打印所有会话值
- javascript - Node Express 不处理并行请求
- java - Java 自动生成属性的方法
- javascript - Angular:Typescript:未捕获的TypeError:无法设置未定义的属性'autoTable'
- arrays - 无法读取 Angular 中未定义的属性“单位”