【发布时间】:2018-10-30 01:01:03
【问题描述】:
您好,我正在尝试在数组的各个元素中添加行和列。我可以添加行但不能添加列。下面我有一个二维数组,添加行的循环产生了我想要的结果,但是我不能将列的元素加在一起。我很难做到这一点,我无法弄清楚如何将所有数字相加,并希望有人可以帮助我解决这个问题。提前致谢。这是代码。
#include <iostream>
using namespace std;
int main()
{
const int ROW1 = 29;
const int COL1 = 5;
int days[ROW1][COL1] =
{
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
{ 1, 2, 3, 4, 5 },
};
//code that sums each row in the array and displays the results.
for (int k = 0; k < ROW1; k++)
{
int rowAdder = 0;
for (int l = 0; l < COL1; l++)
{
rowAdder += days[k][l];
}
cout << "The total of row " << k + 1 << " is " << rowAdder << "." << endl;
}
cout << endl;
//code that sums each column in the array and displays the results.
for (int m = 0; m < ROW1; m++)
{
for (int n = 0; n < COL1; n++)
{
int columnAdder = 0;
columnAdder += days[m][n];
cout << columnAdder << endl;
}
}
return 0;
}
行的输出如下:
The total of row 1 is 15.
The total of row 2 is 15.
The total of row 3 is 15.
The total of row 4 is 15.
The total of row 5 is 15.
The total of row 6 is 15.
The total of row 7 is 15.
The total of row 8 is 15.
The total of row 9 is 15.
The total of row 10 is 15.
The total of row 11 is 15.
The total of row 12 is 15.
The total of row 13 is 15.
The total of row 14 is 15.
The total of row 15 is 15.
The total of row 16 is 15.
The total of row 17 is 15.
The total of row 18 is 15.
The total of row 19 is 15.
The total of row 20 is 15.
The total of row 21 is 15.
The total of row 22 is 15.
The total of row 23 is 15.
The total of row 24 is 15.
The total of row 25 is 15.
The total of row 26 is 15.
The total of row 27 is 15.
The total of row 28 is 15.
The total of row 29 is 15.
我希望第二个循环具有类似的输出,但如果您运行代码,数字不会相加,它会计算单个元素。反而。再次感谢。
【问题讨论】:
-
一台计算机完全按照您的要求执行,而不是您希望它执行的操作。您告诉计算机执行两个嵌套的
for循环,然后在第二个循环内:1)将columnAdder设置为0。2)将单元格的值添加到其中; 3) 打印结果。这正是您的计算机所做的。显然,这不会增加任何列。这发生在矩阵中的每个单独的单元格中。如果您真的想将每列中的所有值相加,则必须有一个for循环来执行此操作。 -
为什么是 29 行?我很确定你可以用 2、3 顶来证明这个问题。
-
也许回顾一下行加法器是如何工作的,并考虑如何对列做同样的事情。
标签: c++ arrays algorithm multidimensional-array