此问题已在此处有答案:
srand() — why call it only once?(7个回答)
4天前关闭。
我想在0和9之间快速创建新的随机数。为此修改了我在那里找到的代码:Why do I always get the same sequence of random numbers with rand()?并将其集成到循环中
我得到的输出是
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
相反,我想得到这样的东西:
Random fast seeded: 2
Random fast seeded: 8
Random fast seeded: 4
Random fast seeded: 7
Random fast seeded: 3
Random fast seeded: 1
Random fast seeded: 3
Random fast seeded: 5
Random fast seeded: 1
Random fast seeded: 9
下面是代码
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main ()
{
struct timespec ts;
for (int i = 0; i<10; i++){
clock_gettime(CLOCK_MONOTONIC, &ts);
srand((unsigned int)ts.tv_nsec);
printf ("Random fast seeded: %d\n", rand()%10);
}
return 0;
}
我做错了什么?
1条答案
按热度按时间aemubtdh1#
将这两个语句
在for循环之前。