4

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

John
  • 2,838
  • 7
  • 36
  • 65
  • 1
    @SleuthEye Well, that would introduce bias... – autistic Apr 01 '15 at 02:50
  • **Clarification needed**: Are you after the unpredictable kind of random (where for all we know, the same value could appear over and over again ad infinitum), or the evenly distributed kind of random (more like the shuffling of a deck of cards)? – autistic Apr 01 '15 at 02:54

1 Answers1

9

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

Community
  • 1
  • 1
SleuthEye
  • 14,379
  • 2
  • 32
  • 61