How do I generate a random number between 0 and 1?
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
man 3 drand48 is exactly what you asked for.
The drand48() and erand48() functions return non-negative, double-precision, floating-point values, uniformly distributed over the interval [0.0 , 1.0].
These are found in #include <stdlib.h>
on UNIX platforms. They're not in ANSI C, though, so (for example) you won't find them on Windows unless you bring your own implementation (e.g. LibGW32C).