因此,在为学校项目编写这一简单的代码行时,我遇到了一个问题。发生的事情是,在请求用户输入以使用值填充数组之后,最后一列的输入将覆盖所有其他列。我自己试过找到问题,但我似乎无法找到它!
我认为部分代码存在问题:
for (col = 0; col < arraywidth; col++) {
for (row = 0; row < arrayheight; row++) {
cout << "Please input a value for element " << col << ", " << row << "." << endl;
cin >> T[col][row];
}
}
感谢您的帮助。这是完整的代码:
#include <iostream>
using namespace std;
int main()
{
// ------------- Variables ---------------------------------
int arrayheight, arraywidth, col, row, maxe, pos_c, T[arrayheight][arraywidth];
// ---------------------------------------------------------
// ------------- Array Creation & Filling ------------------
cout << "Please insert the height of the array." << endl;
cin >> arrayheight;
cout << "Please insert the width of the array." << endl;
cin >> arraywidth;
cout << "Now we will be inputting values in the two-dimensional array." << endl;
for (col = 0; col < arraywidth; col++) {
for (row = 0; row < arrayheight; row++) {
cout << "Please input a value for the element " << col << ", " << row << "." << endl;
cin >> T[col][row];
}
}
// ---------------------------------------------------------
// ------------- Displaying the Array ----------------------
cout << "Now we will be displaying the array." << endl;
for (col = 0; col < arraywidth; col++) {
cout << endl;
for (roaw = 0; row < arrayheight; row++) {
cout << T[col][row] << " | ";
}
}
// ---------------------------------------------------------
// ------------- Logical Function as Requested -------------
cout << " " << endl;
for (col = 0; col < arraywidth; col++) {
maxe = -99;
for (row = 0; row < arrayheight; row++) {
if (T[col][row] > maxe) {
maxe = T[col][row];
pos_c = col;
}
}
cout << "The maximum value of the column " << col << " " << "is " << maxe << endl;
}
// ---------------------------------------------------------
return 0;
}
发生的事情的图片:
答案 0 :(得分:1)
在分配给这些变量之前,您已拥有数组t[arrayheight][arraywidth]
的声明。在从用户读取变量之后,您需要将该声明向下移动。
此外,C ++不允许使用可变长度数组 - 这是G ++扩展。您应该使用std::vector<std::vector<int>>
或动态分配new
。