首页 > 解决方案 > 如何对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

标签: c++

解决方案


在while循环外创建一个全局变量,然后像这样sum = 0然后在循环内sum = sum + output.and在循环外打印值。


推荐阅读