| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

SeedRand

Page history last edited by Kenneth Finnegan 14 years, 9 months ago

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.