mercredi 20 avril 2016

generate random float number ranging [01] in c

When I used rand() with srand() to generate random number in [0,1], it gave me numbers like: 0.70324, 0.70328, 0.70321...

They were difference only in the last one or two digits, while I was intended to get random float numbers like 0.1,0.7,0.3....

How could I get random float number like that instead of making difference in the last digit?

Here's my code:

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

int main(){
    int i;
    float randomNum;
    for (  i=0; i<10; i++){
        srand((unsigned int)time(NULL));
        randomNum = ((float)rand())/RAND_MAX;
        printf("%f\n",randomNum);
     }
    return 0;
}




Aucun commentaire:

Enregistrer un commentaire