按时间播种的随机数不会改变

Random numbers seeded by time don't change

为了生成0到1之间的随机数,我写了下面的代码:

 double random_0_to_1(){
    srand (time(NULL));
    random();
    return (double)random() / (double)RAND_MAX;
}

int main(){

    for(int i = 0 ; i < 10 ; i++){
        double temp = random_0_to_1();
        printf("%f\n", temp);
    }
    return 0;
}

不管我调用多少次,生成的结果总是一样的。始终生成相同的数字。我尝试了很多不同的方法,但似乎找不到任何有效的方法。有没有办法生成每次调用时都不同的随机数 random_0_to_1?

您的代码中存在三个错误:

  1. 您不止一次致电 srand。您应该只在 main.
  2. 的开头调用 srand 一次
  3. 您正在使用 srand 初始化 RNG,但随后调用 random,它使用不同的、不相关的 RNG。你应该打电话给 rand.
  4. 您没有包含必要的 headers、<stdlib.h><time.h><stdio.h>,因此您的代码具有未定义的行为。