I would like to generate some random numbers, say from min
to max
. The problem is that rand()
generates numbers in the range [0, RAND_MAX]
. Scaling this to [min, max]
leads to a range of 1 for each number except for max
which occurs once out of RAND_MAX
times. If I make the upper bound max + 1
, I might still get max + 1
as a value. Basically, is there a way to make the range [min, max + 1)
?
Here's some code I have:
int u_rand(int min, int max)
{
return (int)((double)rand() / RAND_MAX * (max - min + 1)) + min; //has a chance to spit out max + 1
}