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?
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.
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.
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.
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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.