【发布时间】:2015-02-08 19:14:20
【问题描述】:
我正在尝试制作一个策划游戏。用户必须猜测随机生成的颜色。
我写了随机方法,但它总是从相同的元素开始,接下来的 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;
}
【问题讨论】:
-
gen_rand不“返回 0 到 99 范围内的随机数” -
是的 99 应该是 6 :p
-
也可以观看这个视频...channel9.msdn.com/Events/GoingNative/2013/…
-
其实99和6应该是7……他的数组有7种颜色。当然,将 srand() 放在 main() 中。