I'm trying to find a set of random numbers between 1 and 365, so I tried to use:

DayOfBirth = rand() % 365 + 1;

But, I've been told that srand() will produce a better random number, is this true? How do I use it for this instance?

#include <ctime> Then anytime before you use rand put this statement into your program once: srand((unsigned)time(0)); This gives rand a seed based on the current time.

Edited 6 Years Ago by jonsca: n/a

srand() seeds the rand() function. a good way to get a random seed is to use the time function because it changes every time you use it. it should be used as follows for general uses

//...
srand(time(NULL));
value = rand() % 365 + 1;
//...

you will need to include ctime in order to do this. for better and and more reliable random number generators i would search Google. a good one is the mesner twister.

Edited 6 Years Ago by NathanOliver: n/a

a good one is the mesner twister

It's called the Mersenne Twister.

Just a quick note on the cast in my srand call -- srand ideally takes an unsigned int but time comes back with a one that is of type time_t, which is normally a typedef of integer. srand() may generate a warning otherwise.

Edited 6 Years Ago by jonsca: time_t

Comments
thanks for the corrction

thanks for that jonsca. i thought my rand call looked a little light. also thanks for correcting my spelling. i can never get that one right and Ive used it a few times. just doesn't stick right in my head.

No biggie. Wasn't trying to be a stickler I just know that often the next post after it could have been "can't find it."

>>But, I've been told that srand() will produce a better random number

Whomever told that to you should not talk about programming anymore.
All srand does is seed the random number generator.

>>a good one is the mesner twister
>>It's called the Mersenne Twister.

Yes that is better than rand, however usually, rand should suffice for
newbies.

This article has been dead for over six months. Start a new discussion instead.