-
Random generator 0 1
Hi
I'd like to write a random number generator between 0 and1.
I'm doing like that:
Code:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int b;
float r;
srand(time(NULL));
printf("%d",RAND_MAX);
for (b=11;b>0;b--){
r=rand();
printf("%f\n", r/RAND_MAX);
}
return 0;
}
but i get this output:
Code:
21474836470.216477
0.471353
0.312465
0.644094
0.796645
0.112260
0.999378
0.374815
0.463826
0.021919
0.175329
why the first one is not normalized?
Thanks
D.
-
You printed RAND_MAX without a newline, so you confused that and the very first pseudorandom number printed. Try:
Code:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int b;
float r;
srand(time(NULL));
printf("%d\n", RAND_MAX);
for (b=11;b>0;b--){
r = rand();
printf("%f\n", r/RAND_MAX);
}
return 0;
}
-
many thanks, I made an easy error.
D.
-
By the way, the range you get is [0.0, 1.0], but [0.0, 1.0) is more commonly used, methinks. If you want the latter, you would have to say, add 1.0 to RAND_MAX in the divisor.