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

c, random

Solution

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.

Problem

``` srand(time(null)); printf("%d", rand()); ``` Gives a high-range random number (0-32000ish), but I only need about 0-63 or 0-127, though I'm not sure how to go about it. Any help?

Original source

Related problems