Skip to main content
GameDev.net gamedev.net
🔒 Locked

Random Numbers

Started by vbisme Oct 29, 2000 at 12:27 AM 1 replies 250+ views
Original Post
vbisme
vbisme
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
Ironblayde
Ironblayde
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!"
FordPrefect
FordPrefect
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)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.