View Full Version : Best way to select a bounded random number.

I'm not exactly sure how to approach this problem, but I want to generate a random number, which would be range between 0 - 99. I know that to have a random number, I need to initialize it with a seed, so I chose to seed it with time. However, I don't know how to ensure that the random number falls between 0 - 99.

Also, is there a better way to do this? And if so, how so? Thanks in advice.

Most languages have a built-in rand() function.

So, floor(100*rand()) would give you an integer between 0 and 99.

By using the rand function, I always seem to get the same number. And then using the *100, it just multiplies the random number by 100.

Any other ideas?

If you keep getting the same random number, then you need to seed the random number generator (usually done with the current time).

As for multiplication by 100, most rand() functions return a number between 0 and 1. Multiplying by 100 shifts the decimal point over by 2, mapping the original numbers of 0.00... - 0.99... to 0.... - 99....

Then, you simply call floor to truncate the decimal part, leaving 0-99.

Powered by vBulletin® Version 4.2.2 Copyright © 2017 vBulletin Solutions, Inc. All rights reserved.