考虑这段代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int ctr;
for(ctr=0;ctr<=10;ctr++)
{
int iSecret;
srand ( time(NULL) );
printf("%d\n",iSecret = rand() % 1000 + 1);
}
}
它输出这个: 256 256 256 256 256 256 256 256 256 256
不幸的是,我希望输出在该循环中打印 10 个不同的随机数。
最佳答案
将对 srand(time(NULL));
的调用移动到 for
循环之前。
问题是 time()
每秒仅更改一次,但您生成了 10 个数字,除非您的 CPU 非常慢,否则它会赢花点时间生成这 10 个随机数。
所以你每次都用相同的值重新播种生成器,使其返回相同的数字。
关于c - 如何在一个运行时生成不同的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14795209/