填充2d数组随机ints相同的数字

时间:2013-12-23 03:50:50

标签: 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

3 个答案:

答案 0 :(得分:3)

错误发生在您的打印循环中,而不是您的初始化。

  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]<<" ";
    }
  }

另一个小用法提示:请勿在{{1​​}}功能中拨打srand()。如果您在任何地方拨打电话,请在开头附近的createArray()中进行调用,并将其设置为代码中唯一可以调用的位置。

答案 1 :(得分:1)

您的代码有几个错误:

  1. 打印范围错误。必须是array[row][col]
  2. 每次调用函数时都不要初始化srand()。这是一个很大的错误。
  3. 不要使用模数来获取随机数。乘以除法:100.0 * rand() / static_cast<double>(RAND_MAX)
  4. 请!释放您分配的内存。调用delete以释放您创建的阵列(首先释放内部阵列,最后释放主阵列)

答案 2 :(得分:0)

在您的主rowcols中,它们只是数组的维度。 您必须根据corrdinates打印值:

for(int x=0;x<row;x++){
    cout<<endl;
    for (int y=0;y<col;y++){
        cout<<array[x][y]<<" ";
    }
}
cout<<endl;

如果你想反向打印arry,你必须这样做

for(int x=0;x<row;x++){
    cout<<endl;
    for (int y=0;y<col;y++){
        cout<<array[row-1-x][row-1-y]<<" "; // not row-1 and cols-1 as they're not changing
    }
}
cout<<endl;
相关问题