Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Best way to select a bounded random number.

1. ## 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.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•