Jump to content
  • Advertisement


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


Random Numbers

This topic is 6449 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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:


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

 Aeon Software

The following sentence is true.
The preceding sentence is false.

Share this post

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

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!