首页 > 解决方案 > 随机函数如何在 C 中真正起作用?

问题描述

我的程序每次运行时都会返回相同的值:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int randomNum = rand() % 100;
  printf("random number: %d", randomNum);
}

为什么会这样,我该如何解决?

标签: c

解决方案


这是因为rand它是一个伪随机数生成器,这意味着它为任何给定的输入返回相同的序列(输入默认为 1)。

您可以在每次运行程序时为随机数生成器播种时间以获得不同的值:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    struct timespec ts;

    timespec_get(&ts, TIME_UTC);

    srand(ts.tv_sec ^ ts.tv_nsec);

    int random_num = rand() % 100;
    printf("random number: %d", random_num);
}

如果您有 POSIX,您还可以添加一个+ getpid()tosrand的参数和#include <stdlib.h>.


推荐阅读