c stdlib.h 中 RAND_MAX 和 rand() 的说明

clarification for RAND_MAX and rand() in c stdlib.h

为什么当 RAND_MAX 的值显示为 0.000000RAND_MAX 不应该为 rand() 函数生成的数字设置最大值吗?

    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {

    double a,b,c;
    for (int i=0;i<100;i++){
    a=(double)rand()/(double)RAND_MAX;
    b=(double)rand()/(double)RAND_MAX;
    c=a-b;
    printf("itteration : %d values a=%f,b=%f,c=%f, RAND_MAX=%f \n",i,a,b,c,RAND_MAX);
    }  
    return 0;
    }

RAND_MAX 是一个整数常量,但您使用 %f 说明符(用于 double)打印它,这是未定义的行为(在您的情况下恰好打印0).使用 %d,您将看到 RAND_MAX 的实际值。

顺便说一句,如果您将警告设置得足够高,几乎任何体面的编译器都会警告您无效 printf。一定要这样做,C和C++的陷阱够多的,至少让编译器在它能帮你的时候帮你。

...the value for RAND_MAX appears to be 0.000000.

您正在使用双精度说明符打印整数。这是未定义的行为。

来自 C99 标准 (N1256)。

7.19.6.3 The printf function
...
2. The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.

7.19.6.1 The fprintf function
....
9. If a conversion specification is invalid, the behaviour is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

所以它为 RAND_MAX 打印 0.000。你的另一个问题:

Shouldn't RAND_MAX set the maximum value for the number generated by rand() function ?

rand() returns一个在0RAND_MAX范围内的伪随机数。 RAND_MAX 是一个常量,其默认值可能因实现而异,但至少被授予 32767.

但是 rand()RAND_MAX 的浮点除法将产生 01 之间的值。

RAND_MAX 是一个整数,当您使用 %f 打印它时,它在二进制中被截断。实际上,0就是二进制中RAND_MAX的最后几位十进制显示的