Gregor Sturm
Gregor Sturm

Reputation: 2910

Random double in loop stays constant

I have the following c-program to generate random numbers in a loop. While this works well for integers, when I try to generate a random double between 0 and 1, the value stays constant throughout the loop.

Source:

#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); 
    }
}

Output:

>gcc -O3 -o test test.c -lm 
>./test
787380606
1210256636
1002592740
1410731589
737199770
-684428956
-684428956
-684428956
-684428956
-684428956

Upvotes: 3

Views: 100

Answers (1)

Bathsheba
Bathsheba

Reputation: 234695

The behaviour of your code is undefined.

(double) rand() / RAND_MAX is an expression of type double. That requires a %f format specifier in your printf call.

(Also note that (double) rand() / RAND_MAX can draw 1.0 which is idiosyncratic. Normally you write RAND_MAX + 1 on the denominator.)

Upvotes: 6

Related Questions