我正在尝试使用0到100之间的随机数填充二维数组;
另外,我正在尝试输出行的索引以输出行的单元格内的随机值。
我需要的帮助是显示此输出:
示例运行
The sum of row0 elements {41 + 67 + 34 + 0 + 69} is 211
The sum of row1 elements {24 + 78 + 58 + 62 + 64} is 286
The sum of row2 elements {5 + 45 + 81 + 27 + 61} is 219
The sum of row3 elements {91 + 95 + 42 + 27 + 36} is 291
The sum of row4 elements {91 + 4 + 2 + 53 + 92} is 242
检查我的代码:
#include <iostream>
#include <ctime>
int const row = 5;
int const col = 5;
void input (int [][col]);
void output(int [][col]);
using namespace std;
int main()
{
srand(time(0));
int array[row][col] = { 0 };
input (array);
output(array);
system("pause");
return 0;
}
void input(int array [row][col])
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
array[i][j] = rand() % (100 - 1 + 1) + 1;
}
}
}
void output(int array[row][col])
{
int sum;
for (int i = 0; i < row; i++)
{
sum = 0;
cout << "The sum of row" << i << " elements is {" << array[i][0];
for (int j = 1; j < col; j++)
{
sum += array[i][j];
cout << " + " << array[i][j];
}
cout << "} is " << sum << endl;
}
}
答案 0 :(得分:1)
用这个
替换output()函数void output(int array[row][col])
{
int sum;
for (int i = 0; i < row; i++)
{
sum = 0;
cout << "The sum of row" << i << " elements {" << array[i][0];
for (int j = 1; j < col; j++)
{
sum += array[i][j];
cout << " + " << array[i][j];
}
cout << "} is " << sum << endl;
}
}
这样做可以摆脱int total
变量。 int indexi
也未被使用。