Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number in range [min,max] [duplicate]

Tags:

c

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

like image 721
John Avatar asked Oct 21 '25 04:10

John


1 Answers

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).

like image 87
SleuthEye Avatar answered Oct 23 '25 20:10

SleuthEye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!