The way I learned was to initially seed the random number generator with srand(time(NULL))
and then use calls to rand()
to generate random numbers. The problem with this approach is if I run my program multiple times in the same second, the random numbers generated will always be the same. What is a good way around this?
On POSIX systems, use clock_gettime
to get the current time in nanoseconds. If you don't need a lot of bits, you can just forget the PRNG and use the low-order bits of the time as your random number directly. :-)