c++ - 如何对while循环内的输出求和
问题描述
我有一个包含随机整数“框”的代码。我需要在 while 循环中对这些整数求和。
我尝试在 while 循环中使用“for 循环”,但它不起作用。
int i = 1;
while (i <= chambers ){
//chambers = chambers + 1;
boxes = (rand() % 100) + 1;
cout << "In chamber number " << i << " you found "
<< boxes << " boxes of gold!" << endl;
i++;
}
示例输出:
I need to sum the 'boxes': Output Example:
In chamber number 1 you found 8 boxes of gold!
In chamber number 2 you found 50 boxes of gold!
In chamber number 3 you found 74 boxes of gold!
In chamber number 4 you found 59 boxes of gold!
In chamber number 5 you found 31 boxes of gold!
In chamber number 6 you found 73 boxes of gold!
There are 295 boxes of gold in this cave
解决方案
在while循环外创建一个全局变量,然后像这样sum = 0然后在循环内sum = sum + output.and在循环外打印值。
推荐阅读
- android - Android - 在使用带有导航组件的 CollapsingToolbar 时自定义处理导航
- iis - IIS 与任务管理器的内存消耗
- excel - 在 Excel 中修剪空格而不丢失格式
- aws-cdk - 如何将自定义 Lambda 层包含到管道堆栈中?(AWS-CDK)
- r - 了解 R 中 agrep 模糊匹配中的约束
- python - Tensorflow 给出“ValueError:检查输入时出错”
- javascript - React-Native 如何将我的 json 数据返回到我的道具?
- redis - Redis RPUSH - 特定的返回值语义
- r - 我无法取回被排除在插补模型之外的变量 (impute.transcan)
- c# - 在 WrapPanel 中将 DataTables 绑定到 DataGrids