我试图在数组的每列中的某些范围之间随机获取一个随机数,以便模仿宾果卡。
第一列应包含1到10的数字,第二列应包含11到20的数字,第三列应包含21到30,依此类推,直到最后一列,其中包含从81到90的数字。
以下是我根据以下答案修改的代码:
for (row = 0; row<3; row++)
{
for (col = 0; col<9; col++)
{
if (col == 0)
{
bingoCard[row][col] = (rand() % 10) + 1 + col * 10;
}//end of 1st col
else if (col == 1)
{
bingoCard[row][col] = (rand() % 10) + 1 + col * 10;
}//end of 2nd col
else if (col == 2)
{
bingoCard[row][col] = (rand() % 10) + 1 + col * 10;
}//end of 3rd col
else if (col == 3)
{
bingoCard[row][col] = (rand() % 10) + 1 + col * 10;
}//end of 4th col
else if (col == 4)
{
bingoCard[row][col] = (rand() % 10) + 1 + col * 10;
}//end of 5th col
else if (col == 5)
{
bingoCard[row][col] = (rand() % 10) + 1 + col * 10;
}//end of 6th col
else if (col == 6)
{
bingoCard[row][col] = (rand() % 10) + 1 + col * 10;
}//end of 7th col
else if (col == 7)
{
bingoCard[row][col] = (rand() % 10) + 1 + col * 10;
}//end of 8th col
else if (col == 8)
{
bingoCard[row][col] = (rand() % 10) + 1 + col * 10;
}//end of 9th col
}// end col for
现在代码输出以下内容:
***New Game***
How many players?
1
Player : 1 's card
2 18 25 5 16 26 8 17 22
5 16 26 8 17 22 35 43 54
8 17 22 35 43 54 63 73 82
一旦超过第3列,它仍然有效吗?从那里每列中有一个值是对的吗?
答案 0 :(得分:1)
这是一种执行非常简单任务的复杂方法
获取范围内的随机数很简单(rand() % range_size) + range_start
。
下面
for (col = 0; col < 9; col++)
{
for (row = 0; row < 3; row++)
{
bingoCard[row][col] = rand() % 10 + (col * 10 + 1);
}
}
答案 1 :(得分:0)
您实际上只生成0-9之间的随机数,并在其中添加&#34; base&#34;每列。这是一个完整的例子;
#include <stddef.h>
#define ROWS 3
#define COLS 9
int bingoCard[ROWS][COLS];
main()
{
int col, row;
srand(time(NULL));
for (row = 0; row<ROWS; row++)
{
for (col = 0; col<COLS; col++)
{
bingoCard[row][col] = (rand() % 10) + 1 + col*10;
}
}
for (row = 0; row<ROWS; row++)
{
for (col = 0; col<COLS; col++)
{
printf("%d\t", bingoCard[row][col]);
}
/* put a newline */
puts("");
}
}