c++ - 填充二维数组随机整数相同的数字

标签 c++ arrays random multidimensional-array 2d

我正在尝试创建一个充满随机整数的二维数组。行数和列数由用户决定。问题是当我运行程序时,数组中的每个点都填充了相同的数字。

#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/

相关文章:

ios - 在iOS中不重复随机数?

c++ - 如何从时间戳间隔获取天数列表

c++ - 如何将文件路径和参数的执行路径分开?

c++ - C++ 在多大程度上是一种静态类型语言?

c++ - 如何使用带有 ISO14443 层的 T=CL(ISO7816) 协议(protocol)发送 APDU 命令

ios - 索引还是标签?对于多个复选框作为 IBOutletCollection 中的按钮

Javascript:像搜索查询字符串一样解析数组

c - 指针数组问题

c# - 从没有重复元素的数组字符串中获取随机 8 个元素值

c++ - 在多个函数中使用相同的随机数生成器