如何对 while 循环内的输出求和
How to sum the output inside the while loop
我有一个包含随机整数'盒子'的代码。我需要在 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 循环结束时,运行总计将是所有框的总和。
int total_boxes = 0;
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;
total_boxes += boxes; // total boxes so far
i++;
}
cout << "There are " << total_boxes << " boxes of goldn";
在循环时在外面做一个全局变量,并像这样做sum = 0,然后在循环内 sum=sum+output.并在循环的一侧打印值。
使用辅助变量,如 boxes_total
。 在输入 while 之前对其进行初始化boxes_total=0
并在 while boxes_total = boxes_total + boxes
结束时添加。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 如何对 while 循环内的输出求和
- OpenACC求和减少在每次执行时输出递增求和