二维数组平均和总c++

2d array average and total c++

它必须如下所示:

#include <iostream>

using namespace std;

int main()
{


    float allsales[3] [2] = {{1200.33, 2350.75}, {3677.80, 2456.05}, {750.67, 1345.99}};
    float totalsales = 0, ave = 0, sum = 0;



       for (int row = 0; row < 3; row++)
       {
           cout << "Ave sale for store "<< row + 1 << ": ";

        for (int col=0; col < 2; col++)
        {


           totalsales += allsales [row] [col];
           sum = 0; // I cant figure out how to code the formula for the sum
           ave = sum / 2;
           cout << ave <<endl;


        }

        

    }

    cout << "Total sales : $" << totalsales << endl;
    return 0;
}

此外,我是一名一年级学生,所以我不能使用一些高级 codes/commands 等。我只能坚持嵌套 for 循环,否则,while

float allsales[3] [2] = {{1200.33, 2350.75}, {3677.80, 2456.05}, {750.67, 1345.99}};
float totalsales = 0, ave = 0, sum = 0;

   for (int row = 0; row < 3; row++)
   {
       cout << "Ave sale for store "<< row + 1 << ": ";
       sum = 0;
       for (int col=0; col < 2; col++)
       {
            totalsales += allsales[row][col];
            sum += allsales[row][col];
       }
        ave = sum / 2;
        cout << ave <<endl;
    }

cout << "Total sales : $" << totalsales << endl;
return 0;

sum 和 totalsales 的唯一区别是 sum 一次只针对一行,因此需要在第二次循环开始之前将其初始化为零。在内循环之后还需要计算平均值,一旦计算完一行总和。

尝试干运行代码以更好地理解循环

你会怎么做?

I 将开始 sum 每行的初始值为零,向其添加该行中的每个元素,然后在最后计算平均值该行。

(别忘了您可以在函数中第一处以外的其他地方声明变量。)

我也可能会先对行求和,然后将“行总和”加到总数中。

像这样:

for (int row = 0; row < 3; row++)
{
    float sum = 0;
    for (int col = 0; col < 2; col++)
    {
        sum += allsales[row][col];
    }
    cout << "Ave sale for store "<< row + 1 << ": " << sum / 2 << endl;
    totalsales += sum;
}