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

时间:2019-02-13 06:05:24

标签: c++

我有一个包含随机整数“ boxes”的代码。我需要将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

3 个答案:

答案 0 :(得分:0)

在while循环外制作一个全局变量,并像这样做 sum = 0,然后在循环内进行sum = sum + output。然后在循环外打印该值。

答案 1 :(得分:0)

使用辅助变量,例如boxes_total。在将while输入boxes_total=0之前对其进行初始化,然后在while boxes_total = boxes_total + boxes的末尾添加。

答案 2 :(得分:0)

像这样,添加一个新变量来容纳连续运行的盒子总数。在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 gold\n";