如何对 while 循环内的输出求和

How to sum the output inside the while loop

本文关键字:输出 求和 循环 while      更新时间:2023-10-16

我有一个包含随机整数'盒子'的代码。我需要在 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结束时添加。