我是 C++ 的新手,我必须解决一个大学任务,我必须创建一个结构矩阵并用随机整数填充它。我用“!”标记了这一行出现错误的地方。 这是错误 C2131(Visual C++ 编译器)。它说“表达式未计算为常量”。
struct Matrix{
int rows;
int columns;
Matrix(int r, int c){
rows = r, columns = c;
}
int produceMatrix(){
int matrix[rows][columns]; "!"
for(int i = 0; i != rows; i++){
for(int j = 0; j != columns; j++){
matrix[i][j] = rand() %10 +1;
}
}
return 0;
}
int showMatrix(){
for(int i = 0; i != rows; i++){
for(int j = 0; j != columns; j++){
cout << matrix[i][j]<< endl;
}
}
}
};
int main()
{
srand(time(0));
Matrix a(3, 4);
}
最佳答案
如果您计划使用 rows
创建矩阵和 columns
仅在运行时已知的值,您最好使用 std::vector<std::vector<int>>
来保存你的数据,因为你使用的静态数组需要在编译时知道它的大小。但是如果你所有的大小在编译时都是已知的并且你只是想灵活地创建不同的矩阵大小,你可以使用模板,例如:
#include <iostream>
#include <ctime>
template <int ROWS, int COLUMNS>
struct Matrix
{
int rows = ROWS;
int columns = COLUMNS;
int matrix[ROWS][COLUMNS] = {};
void produceMatrix()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
matrix[i][j] = rand() % 10 + 1;
}
}
}
void showMatrix()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
std::cout << matrix[i][j] << "\t";
}
std::cout << std::endl;
}
}
};
int main()
{
srand(time(0));
Matrix<3,4> a;
a.produceMatrix();
a.showMatrix();
}
4 10 5 5
3 8 3 6
2 4 9 10
关于c++ - 有人可以解释一下,为什么我的代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50542836/