mercredi 29 novembre 2017

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.

  • Why does that happen?
  • How can I generate a random double in [0, 1] within a loop?

Source:

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

int main(int argc, char** argv) {
    srand(time(NULL));
    for(int i; i<5; i++) {
        printf("%d\n", rand()); 
    }
    for(int i; 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




Aucun commentaire:

Enregistrer un commentaire