Hello.
I want to make a program that, given the minimum value and the maximum value, generates a random number within that range.
I made that with this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
#include <conio.h>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
int min = 0, max = 2;
int val = ((max + 1) - min) + min;
int num = rand() % val;
cout << "Random number: " << num << endl;
cout << "Value: " << val << endl;
_getch();
return 0;
}
|
If you see, the min is 0 and the max is 2.
The second COUT (that prints the final value) prints
3
Now, if I change the range from 0-2 to 1-2, the second cout
still prints 3
But... if the value is always 3 that means that this code
rand() % val
is equivalent to
rand() % 3
But the point here is that, despite the value is the same, the program has 2 different behaviors
In the first "0-2" case, it prints these values {0,1,2}
In the "1-2" case, it prints these ones {1,2}
How can the program work in 2 different ways with the same value (3)???