If you've ever used the stdlib.h rand() function, you've probably noticed that every time you run your program, it gives back the same results. This is because, by default, the standard (pseudo) random number generator is seeded with the number 1. To have it start anywhere else in the series, call the function srand(unsigned int seed). For the seed, you can use the current time in seconds.
Code:
#include <time.h>
// At the beginning of main, or at least before you use rand()
srand(time(NULL));
Extensions:
Note that this seeds the generator from the current second. This means that if you expect your program to be rerun more than once a second (some kind of batch processor or simulator maybe), this will not be good enough for you. A possible workaround is to store the seed in a file, which you then increment every time the program is run.
When you're using random numbers, be very considerate about what you're using them for, and how random they need to be. The standard library rand() function may or may not be good enough for what you're using it for (ie gambling, cryptogaphy, etc)
Sources:
Comments (0)
You don't have permission to comment on this page.