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

11-05-2008, 03:22 AM
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.

11-05-2008, 04:11 AM
Most languages have a built-in rand() function.

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

11-06-2008, 06:43 AM
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?

11-06-2008, 02:54 PM
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.