gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:23:21 25 4
gpt4 key购买 nike

我能够在 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 相加并产生一个值。任何提示表示赞赏。

最佳答案

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

double grandTotal = 0.0;
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;
grandTotal += totalArray;
}
cout << "The total of all rows is " << grandTotal << "." << endl;

return 0;

关于c++ - 在 C++ 中的二维数组中添加行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50420380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com