考虑以下代码:
#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);
}
}
Run Code Online (Sandbox Code Playgroud)
它输出:256 256 256 256 256 256 256 256 256 256
不幸的是,我希望输出在该循环中打印10个不同的随机数.
小智 6
srand(time(NULL));在for循环之前将呼叫移至.
问题是time()每秒只更改一次,但是你生成了10个数字,除非你的CPU速度非常慢,否则生成这10个随机数就不会花费一秒钟.
因此,您每次都会使用相同的值重新播种生成器,使其返回相同的数字.
| 归档时间: |
|
| 查看次数: |
722 次 |
| 最近记录: |