I am using C to generate a integer random number in range [min max]. I am using
int random_int(int min, int max)
{
return min + rand() % (max - min);
}
But I think above code is for range : [min, max), it is not for [min max]. Could you show to me a code to do my work. Best thanks
As you guessed, the code does indeed generate random numbers which do not include the max value. If you need to have the max value included in the range of random numbers generated, then the range becomes [min,max+1). So you could simply modify your code to:
int random_int(int min, int max)
{
return min + rand() % (max+1 - min);
}
P.S.: that is provided the quality of the original 'modulo' pseudo-random number generator you posted was not a concern (see this post for some more details with respect to what @undefinedbehaviour was referring to in comments).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With