在C ++中添加二维数组中的行和列

时间:2018-05-18 23:25:33

标签: c++

我能够在C ++中一起添加行的元素,并希望在所有行和列中添加所有元素。我写的内容将行的值加在一起,但是分别打印出列。

#include <iostream>
using namespace std
int main() 
{

const int ROW = 10;
const int COL = 20;

int dimenArray[ROW][COL] ={{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}};

for (int i = 0; i < ROW; i++) 
{
    double totalArray = 0.0;

    for (int j = 0; j < COL; j++)
        {
        totalArray += dimenArray[i][j];
        }
    cout <<"The total of dimenArray is " << totalArray << "." << endl;
    }

return 0;
}

我得到的输出是。

The total of dimenArray is 55.
The total of dimenArray is 210.
The total of dimenArray is 0.
The total of dimenArray is 0.
The total of dimenArray is 0.
The total of dimenArray is 0.
The total of dimenArray is 0.
The total of dimenArray is 0.
The total of dimenArray is 0.
The total of dimenArray is 0.

我想将55和210一起添加并生成一个值。任何提示都表示赞赏。

2 个答案:

答案 0 :(得分:2)

你需要另一个变量来表示所有行的总数。

const ctx: Worker = self as any;
ctx.addEventListener('message', (e) => {
    // console.log(e)
    if (e.data === 'do some work') {
        console.log('Worker is about to start some work');
        let count: number = 0;
        for (let i: number = 0; i < 1000; i++) {
            count += i;
        }
        ctx.postMessage({ message: count });
    }
})

答案 1 :(得分:0)

totalArray的声明移到循环之外。

在编辑中添加:即便如此,您写道,

  

我能够在C ++中一起添加行的元素,并希望在所有行和列中添加所有元素。我写的内容将行的值加在一起,但是分别打印出列。

您的循环如下:

for (int i = 0; i < ROW; i++) 
{
    double totalArray = 0.0;

    for (int j = 0; j < COL; j++)
        {
        totalArray += dimenArray[i][j];
        }
    cout <<"The total of dimenArray is " << totalArray << "." << endl;
    }

您应该按如下方式重写:

double totalArray = 0.0;
for (int i = 0; i < ROW; i++) 
{

    for (int j = 0; j < COL; j++)
        {
        totalArray += dimenArray[i][j];
        }
    cout <<"The total of dimenArray is " << totalArray << "." << endl;
    }

这将&#34;添加所有元素&#34;,这就是我的意思&#34;将totalArray的声明移到循环之外。&#34;

OP的后续澄清清楚表明他的意思是其他的东西,但这不是原始问题,实际上仍未编辑。所以这是发布的问题的正确答案(在我编辑之前,代码审查)。