#### Archived

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.

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

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

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 15
• 13
• 9
• 12
• 10
• ### Forum Statistics

• Total Topics
631442
• Total Posts
3000091
×