如何计算2D数组中每行的总和并放置在向量中?

时间:2021-04-04 21:33:00

I am trying to calculate the sum of each row in the array and place it in a vector, You can find my attempt below,

我试图计算数组中每一行的总和并将其放在一个向量中,你可以在下面找到我的尝试,

For that, it prints the same values for the first 4 and a different for the last 1, 215 215 215 215 316

为此,它为前4个打印相同的值,为最后的1打印不同的值,215 215 215 215 316

What I want is for example

我想要的是例如

x1 2 4 4 6 7  Sumx1=??
x2 1 2 3 4 5  etc
x3 1 2 3 4 5 
x4 1 2 4 5 6

and place the value Sumx1 in a vector.

并将值Sumx1放在向量中。

Here's my attempt

这是我的尝试

#include <time.h>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    string name;
    srand(time(NULL));

    int pay[5][4];

    vector<string> names;

    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            pay[i][j] = rand() % 51 + 50;
            cout << pay[i][j] << "  ";
        }
        cout << endl;
    }

    cout << endl << endl;

    vector<int> totals;

    for (int i = 0; i < 5; i++) {
        for (int c = 0; c < 4; c++) {
            totals.push_back((pay[i][0] + pay[i][1] + pay[i][2] + pay[i][3]));
        }
        cout << totals[i] << "  ";
    }

    return 0;
}

2 个解决方案

#1


0  

for(int i=0; i<5; i++){
        for(int c=0; c<4; c++){
            totals.push_back((pay[i][0]+pay[i][1]+pay[i][2]+pay[i][3]));
            }
        cout<<totals[i]<<"  ";
    }

Try removing the inner loop (the one with variable c). Should work.

尝试删除内部循环(带有变量c的循环)。应该管用。

#2


0  

You add the sum pay[i][0]+pay[i][1]+pay[i][2]+pay[i][3] to the vector four times due to your inner loop c.

由于你的内部循环c,你将和pay [i] [0] + pay [i] [1] + pay [i] [2] + pay [i] [3]加到向量四次。

What you really want is the following,

你真正想要的是以下,

for(int i=0; i<5; i++){
    int sum = 0;
    for(int c=0; c<4; c++)
        sum += pay[i][c];
    totals.push_back(sum);
    cout<<totals[i]<<"  ";
}

#1


0  

for(int i=0; i<5; i++){
        for(int c=0; c<4; c++){
            totals.push_back((pay[i][0]+pay[i][1]+pay[i][2]+pay[i][3]));
            }
        cout<<totals[i]<<"  ";
    }

Try removing the inner loop (the one with variable c). Should work.

尝试删除内部循环(带有变量c的循环)。应该管用。

#2


0  

You add the sum pay[i][0]+pay[i][1]+pay[i][2]+pay[i][3] to the vector four times due to your inner loop c.

由于你的内部循环c,你将和pay [i] [0] + pay [i] [1] + pay [i] [2] + pay [i] [3]加到向量四次。

What you really want is the following,

你真正想要的是以下,

for(int i=0; i<5; i++){
    int sum = 0;
    for(int c=0; c<4; c++)
        sum += pay[i][c];
    totals.push_back(sum);
    cout<<totals[i]<<"  ";
}