我正在尝试创建一个充满随机整数的二维数组。行数和列数由用户决定。问题是当我运行程序时,数组中的每个点都填充了相同的数字。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int** createArray(int rows, int cols){
// Create a 2D array of ints that is rows x cols
int** array = new int*[rows];
for(int i = 0;i<rows;++i){
array[i] = new int[cols];
}
// Fill the array
srand(time(NULL));
for(int r = 0; r<rows; ++r){
for(int c = 0;c<cols;++c){
array[r][c] = (rand()%100);
}
}
return array;
}
int main(int argc, char* argv[]){
int** array;
int row = atoi(argv[1]);
int col = atoi(argv[2]);
array = createArray(row,col);
for(int x=0;x<row;x++){
cout<<endl;
for (int y=0;y<col;y++){
cout<<array[row-1][col-1]<<" ";
}
}
cout<<endl;
return 0;
}
输出通常遵循以下内容:
53 53 53
53 53 53
53 53 53
最佳答案
错误出在你的打印循环中,而不是你的初始化。
for(int x=0;x<row;x++){
cout<<endl;
for (int y=0;y<col;y++){
cout<<array[row-1][col-1]<<" ";
}
}
始终打印右下角(第 1 行,第 1 列)。你可能是这个意思:
for(int x=0;x<row;x++){
cout<<endl;
for (int y=0;y<col;y++){
cout<<array[x][y]<<" ";
}
}
还有一个小的使用提示:不要在 createArray()
函数中调用 srand()
。如果您在任何地方调用它,请在开头附近的 main()
中调用它,并使其成为代码中唯一被调用的地方。
关于c++ - 填充二维数组随机整数相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20736731/