C语言 获取瞬时随机数(循环中)[重复]

ehxuflar  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(152)

此问题已在此处有答案

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;
}

我做错了什么?

aemubtdh

aemubtdh1#

将这两个语句

clock_gettime(CLOCK_MONOTONIC, &ts);
srand((unsigned int)ts.tv_nsec);

在for循环之前。

相关问题