关于gnu:c stdlib.h中RAND_MAX和rand()的说明

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

当RAND_MAX的值似乎是0.000000时,为什么以下c代码对于double a,b只产生介于0和1之间的实数(例如:0.840188,0.394383 ...等)。 RAND_MAX是否不应该为rand()函数生成的数字设置最大值?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    #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
"
,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()返回在0RAND_MAX范围内的伪随机数。
RAND_MAX是一个常量,其默认值在不同的实现中可能有所不同,但至少应为32767

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