In your initial case (max-min)
is 0
and modulus by zero is undefined behavior. From the C++ draft standard section 5.6
Multiplicative operators says:
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. [...]
As for generating a random number between min and max
you should use the random header and uniform_int_distrubution:
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 e2(rd());
int min = 1, max = 1 ;
std::uniform_int_distribution<int> dist(min,max);
for (int n = 0; n < 10; ++n) {
std::cout << dist(e2) << ", " ;
}
std::cout << std::endl ;
}
If for some reason C++11 is not an option then the C FAQ gives us the proper formula when using rand
in the section How can I get random integers in a certain range? which indicates to generate random numbers in the range [M, N]
you use the following:
M + rand() / (RAND_MAX / (N - M + 1) + 1)