如何为不同类型的2d数组生成随机数

How to generate a random number for 2d array of a different type?

本文关键字:数组 随机数 2d 同类型      更新时间:2023-10-16

彩色类型的2d阵列

enum color{black, white};
color A[nrow][ncol];

我需要一个随机数生成器,使[I][j]具有"0"或"1",然后我会说:

if (A[i][j]==0)
  {
    A[i][j]=black;
  } 

事情是,我们主要写:

srand(unsigned int (NULL);

所以当我写:

for (int i=0; i<nrow; i++)
{
  for (int j=0; j<ncol; j++)
  {
    A[i][j]= rand () % 2;
  }

一个错误表明int不能分配给类型color。如何解决这个问题?

一个选项是将int转换为彩色

 A[i][j]= (color)(rand () % 2);

其他选项是

 A[i][j]= (rand () % 2) ? white : black;

顺便说一句,我更喜欢

 A[i][j]= (rand () & 1) ? white : black;