随机双循环保持不变

Gre*_*urm 3 c random

我有以下c程序在循环中生成随机数.虽然这适用于整数,但当我尝试生成0和1之间的随机双精度时,该值在整个循环中保持不变.

  • 为什么会这样?
  • 如何在循环中的[0,1]中生成随机双精度?

资源:

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

int main(int argc, char** argv) {
    srand(time(NULL));
    for(int i=0; i<5; i++) {
        printf("%d\n", rand()); 
    }
    for(int i=0; i<5; i++) {
        printf("%d\n", (double) rand() / RAND_MAX); 
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

>gcc -O3 -o test test.c -lm 
>./test
787380606
1210256636
1002592740
1410731589
737199770
-684428956
-684428956
-684428956
-684428956
-684428956
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 6

代码的行为未定义.

(double) rand() / RAND_MAX是一种类型的表达double.这需要%f您的printf通话中的格式说明符.

(另请注意,(double) rand() / RAND_MAX可以绘制1.0哪个是特殊的.通常你会RAND_MAX + 1在分母上书写.)

  • 而``RAND_MAX + 1`?否则它甚至可能> 1 (2认同)