可能的重复:
为什么我总是用 rand() 得到相同的随机数序列? https://stackoverflow.com/questions/1108780/why-do-i-always-get-the-same-sequence-of-random-numbers-with-rand
到目前为止,这是我的文件:
#include <stdio.h>
int main(void) {
int y;
y = generateRandomNumber();
printf("\nThe number is: %d\n", y);
return 0;
}
int generateRandomNumber(void) {
int x;
x = rand();
return x;
}
我的问题是 rand() 总是返回 41。我在 win 上使用 gcc...不知道在这里该怎么做。
编辑:使用时间来生成随机数是行不通的。它为我提供了一个数字(12000 左右),每次我调用它时,它都会高一点(大约每秒 +3)。这不是我需要的随机性。我该怎么办?
你需要给它提供种子。
来自网络 -
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i, stime;
long ltime;
/* get the current calendar time */
ltime = time(NULL);
stime = (unsigned) ltime/2;
srand(stime);
for(i=0; i<10; i++) printf("%d ", rand());
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)