最初指出用户输入三乘三矩阵的值的问题。然后提出了一个挑战来修改程序,以便用户可以指定阵列的尺寸。我尝试了这个问题,我的程序运行正常,但它只打印出用户指定的数组形式的最后一个值。
/*three by three matrix
user enters values
outputs these elements
sums all the elements and outputs the result
*/
#include <iostream>
using namespace std;
int main(){
int i, j;
int r, c = 0;
int matrix[r][c];
int sum;
cout << "A matrix, you want to make.Help I shall, \n";
cout << "ROWS: ";
cin >> r;
cout << "COLUMNS: ";
cin >> c;
cout << "Give me the values of the " << r << " X " << c << " matrix in rows first: ";
cout << "\n";
//user inputs the values
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
cin >> matrix[r][c];
sum = matrix[r][c] + sum;
}
cout << "\n";
}
//outputs the values
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
cout << matrix[r][c] << " ";
}
cout << "\n";
}
cout << "The sum of all these elements is: " << sum;
return 0;
}
答案 0 :(得分:0)
让我们考虑
int main(){
int i, j;
int r, c = 0;
int matrix[r][c];
此处r
未初始化且c
为零。这意味着matrix
具有未知数量的行和零列。请注意,如果您确实想要初始化相同类型的多个变量,通常最好每行执行一次,例如
int r = 0;
int c = 0;
可能最简单的方法是使用评论中提到的向量向量。不幸的是,C ++对多维数组的内在支持相对较差。
答案 1 :(得分:0)
请尝试以下代码:
使用namespace std;
int main(){
int i, j;
int r, c = 0;
int sum=0;
cout << "A matrix, you want to make.Help I shall, \n";
cout << "ROWS: ";
cin >> r;
cout << "COLUMNS: ";
cin >> c;
cout << "Give me the values of the " << r << " X " << c << " matrix in rows first: ";
cout << "\n";
int matrix[r][c];
//user inputs the values
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
cin >> matrix[i][j];
sum = matrix[i][j] + sum;
}
cout << "\n";
}
//outputs the values
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
cout << matrix[i][j] << " ";
}
cout << "\n";
}
cout << "The sum of all these elements is: " << sum;
return 0;
}
您的代码中存在两个问题:
您在开始时初始化矩阵[r] [c]而没有初始化r和c的值。
你在做cin&gt;&gt;矩阵[r] [c]内循环,每次循环运行时得到矩阵[3] [3]的值,因为r = 3且c = 3。而是做cin&gt;&gt;矩阵[i] [j]内循环。
希望这有帮助!!!