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;
}
You should call srand()
only once, at the beginning of your program. Calling it before each call to rand()
only makes the results more predictable, since each time you call it with a number probably very similar to the previous one.