+ 1
modulo (%) operator for rand()
In the example, the Range is set to 1 to 6 by using the modulo %6 while adding 1 to the whole thing. Does that mean, that the modulo will return anything between 0 and <6 which then offsets the range to between 1 to 6 instead of 1 to 7? Is this due to integer as datatype? If I understand correctly, this means a double or float would return values between 1 and 6.9999 (period) when using 1 + (rand() % 6) as shown in the example? So basically the modulo restricts the value between 0 and <modulo, not 0 and <=modulo?
4 Answers
+ 23
You first, have to understand what modulo does. It returns the remainder of a division.
E.g. 5/2 = 2 with remainder 1, hence 5%2 = 1
Assuming rand() returns any number larger than 6, let's take a set of possible numbers: 100, 42, 13, 20.
100 % 6 = 4
42 % 6 = 0
13 % 6 = 1
20 % 6 = 2
(Anything) % 6 can never be greater than, or equal to 6. The range is within 0 to 5.
Hence,
cout << rand() % 6;
will always return values from 0 to 5. By doing
cout << 1 + rand() % 6;
we increase the maximum and minimum range by 1. The resultant range will be 1 to 6.
+ 18
You're welcome. Glad I helped.
+ 1
Ah thanks I missed the connection to the modulo operator as explained before. I thought of it more like an attribute which limits the range, therefore the confusion!
+ 1
Modulo creates a bias towards lower numbers in random number generation. C++11 introduced a better way to generate random numbers using engines and distributions. I have created a code showing an example of how it works: https://code.sololearn.com/cCsaJ7cWOeoA/?ref=app
P.S.: It won't work in some compilers unless you add -std=c++11 to the compiler command line.