Archived

This topic is now archived and is closed to further replies.

vbisme

Random Numbers

Recommended Posts

vbisme    100
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

Share this post


Link to post
Share on other sites
Ironblayde    130
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.

Share this post


Link to post
Share on other sites
FordPrefect    122
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)

Share this post


Link to post
Share on other sites