How do I generate a random number between 0 and 1?
rand() The function rand() is used to generate the pseudo random number. It returns an integer value and its range is from 0 to rand_max i.e 32767.
The rand function, declared in stdlib. h, returns a random integer in the range 0 to RAND_MAX (inclusive) every time you call it. On machines using the GNU C library RAND_MAX is equal to INT_MAX or 231-1, but it may be as small as 32767.
You can generate a pseudorandom number using stdlib.h. Simply include stdlib, then call
double random_number = rand() / (double)RAND_MAX;
Assuming OP wants either 0 or 1:
srand(time(NULL));
foo = rand() & 1;
Edit inspired by comment:
Old rand()
implementations had a flaw - lower-order bits had much shorter periods than higher-order bits so use of low-order bit for such implementations isn't good.
If you know your rand()
implementation suffers from this flaw, use high-order bit, like this:
foo = rand() >> (sizeof(int)*8-1)
assuming regular 8-bits-per-byte architectures
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With