Random Numbers

Started by
1 comment, last by vbisme 23 years, 5 months ago
How do I generate random numbers between 0 and 1? Or better yet, how do I generate intergers between a range? Like if I what random numbers between 10 and 30. C++ functions please. Thanks
Advertisement
The rand() function generates a pseudorandom number between 0 and RAND_MAX, so you can get a random integer between 0 and (x-1) by calling rand(), then computing its value modulo x. For instance, this:

int nRandom = rand() % 10;

generates a random number between 0 and 9. So to generate a random number for any given range, you would use something of this form:

int nRandom = (rand() % (HI - LO + 1)) + LO;

Before using rand(), you must seed the random number generator by using a call to srand(). A good value to pass so you don''t always generate the same series of "random" numbers is the time, so use:

srand(GetTickCount())

You only need to call this function once in your program.

-Ironblayde
 Aeon Software

The following sentence is true.
The preceding sentence is false.
"Your superior intellect is no match for our puny weapons!"
The modulus method is not reccomended because the low order bits of some prngs are very much non-random. a better way to generate a random number in the range 0 to n-1 is:
int)((double)rand() / ((double)RAND_MAX + 1) * N)

This topic is closed to new replies.

Advertisement