我正在尝试制作一款策划游戏。用户必须猜测随机生成的颜色。
我写了 random 方法,但它一直以相同的元素开始,接下来的 3 个是
全部相同但与第一个元素不同(例如 I,o,o,o I,r,r,r
)。如何修复我的代码?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define cLength 6
int gen_rand();
// start of main
int main() {
int i, rNum;
// this is the array for the easy mode
char colours[cLength + 1] = {'r', 'o', 'y', 'g', 'b', 'i', 'v'};
// this is the randomly generated array
char rand[3 + 1] = "";
// this is the guess array that the user will populate
char guess[3 + 1] = "";
// for statement to populate the rand array with random elements in the colours array
rand[0] = colours[gen_rand()];
rand[1] = colours[gen_rand()];
rand[2] = colours[gen_rand()];
rand[3] = colours[gen_rand()];
printf("\n%c", rand[0]);
printf("\n%c", rand[1]);
printf("\n%c", rand[2]);
printf("\n%c", rand[3]);
// for statement to populate the guess array
for (i = 0; i < 4; i++) {
printf("\n Please enter a colour e.g r for Red : ");
scanf("%c", &guess[i]);
fflush(stdin);
}
printf("%c", guess[2]);
printf("\n\n\n");
system("pause");
}
int gen_rand() { // returns random number in range of 0 to 99
int r = rand() % 6;
srand(time(NULL));
return r;
}
最佳答案
您对 srand()
的调用放错了地方,它需要在您使用随机数生成器之前进行,以影响它。
此外,不要使用模数来计算随机数,这是一种糟糕且有问题的方法,通常保证它们不是均匀分布的。
参见 this question有关如何生成更多高质量随机整数的一系列建议。
关于c - C中数组中的随机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27403618/