The modulus operation a % b
computes the remainder of the division a / b
. Obviously the remainder of a division must be less than b
and if a
is a random positive integer then a%b
is a random integer in the range 0 .. (b-1)
In the comments you mention:
rand()%(max-min)+min
This algorithm produces values in the half-open range [min, max). (That is, max is outside the range, and simply denotes the boundary. Since we're talking about ranges of integers this range is equivalent to the closed range [min, max-1].)
When you write '0 - 5' or '6 - 12' those are closed ranges. To use the above equation you have to use the values that denote the equivalent half open range: [0, 6) or [6, 13).
rand() % (6-0) + 0
rand() % (13-6) + 6
Note that rand() % (max-min) + min
is just a generalization of the rule you've apparently already learned: that rand() % n
produces values in the range 0 - (n-1). The equivalent half-open range is [0, n), and rand() % n
== rand() % (n-0) + 0
.
So the lesson is: don't confuse half-open ranges for closed ranges.
A second lesson is that this shows another way in which <random>
is easier to use than rand()
and manually computing your own distributions. The built-in uniform_int_distribution
allows you to directly state the desired, inclusive range. If you want the range 0 - 5 you say uniform_int_distibution<>(0, 5)
, and if you want the range 6 - 12 then you say uniform_int_distribution<>(6, 12)
.
#include <random>
#include <iostream>
int main() {
std::default_random_engine eng;
std::uniform_int_distribution<> dist(6, 12);
for (int i=0; i<10; ++i)
std::cout << dist(eng) << " ";
}
rand()%7+6
is more terse, but that doesn't mean it is easier to use.