How do I get a specific range of numbers from rand()?

rand() % (max_number + 1 - minimum_number) + minimum_number

So, for 0-65:

rand() % (65 + 1 - 0) + 0

(obviously you can leave the 0 off, but it’s there for completeness).

Note that this will bias the randomness slightly, but probably not anything to be concerned about if you’re not doing something particularly sensitive.

Leave a Comment