使用这个程序,我试图将一个 6x15 数组设置为 0,然后在数组的随机槽中放置一个随机数 x 次。然而,事情并没有按计划进行……
注意 MAX_ROWS 为 6,MAX_COLS 为 15,OCEAN 为 0
#include <stdio.h>
#include <time.h>
#include "util.h"
int rand_number(int param);
main()
{
int map[MAX_ROWS][MAX_COLS]; //initializes an array, map, with the dimensions 6 and 15.
//sets all values in the array to 0
int a,b;
for (a = 0; a < MAX_ROWS; a++)
{
for (b = 0; b < MAX_COLS; b++)
{map[a][b]=OCEAN;}
}
int shipnum = 6;
这应该放置随机数。(shipnum 只是我用来限制我放置的船只数量的值):
while(shipnum > 0)
{
map[rand_number(MAX_ROWS)][rand_number(MAX_COLS)] = 3;
shipnum -= 1;
map[rand_number(MAX_ROWS)][rand_number(MAX_COLS)] = 2;
shipnum -= 2;
map[rand_number(MAX_ROWS)][rand_number(MAX_COLS)] = 1;
shipnum -= 3;
}
但是,当我跑步时
/*This will print the array*/
for (a = 0; a < MAX_ROWS; a++)
{
for (b = 0; b < MAX_COLS; b++)
{printf("%d ", map[a][b]);}
printf("\n");
}
}
我被给
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
当我真的想得到类似的东西时
0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 2 0 0 0 0 0 3 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
这是我用来生成随机数的函数。
/*This will generate a random number*/
int rand_number(int param)
{
srand((unsigned int)time(NULL));
int x = param;
int rn = rand() % x;
return rn;
}