1

I am creating a random number generator and whenever I run the current code block I always get a few numbers that go over the intended limit. The way it works is that I have a set of numbers that are randomly generated that go from 36-75, With adjusted numbers that are 5 higher and 5 lower than the original number. For example I will end up with numbers above 75. The highest being 105. Here is just one of the 6 numbers.

//Displays picks for Number 4
pick4 = (rand() % 75) + 36;
if (pick4 == pick3)
    pick4 = (rand() % 75) + 36;
if (pick4 + 5 < 75 + 1)
{
if (pick4 - 5 > 0)
    {
        adjHighPick4 = pick4 + 5;
        adjLowPick4 = pick4 - 5;
    }
}
NeoSanguine
  • 43
  • 1
  • 5

1 Answers1

1

When you want to get a random integer from A to B, you just need a random integer from 0 to B-A, to which you add A. So, instead of rand() % 75 + 36, you should write rand() % 39 + 36 (A=36, B=75, B-A=39)

Rontogiannis Aristofanis
  • 8,883
  • 8
  • 41
  • 58
  • 6
    Please stop propagating this `rand() % something` anti-pattern. – T.C. Feb 15 '15 at 17:02
  • @T.C. What do you mean? – Rontogiannis Aristofanis Feb 15 '15 at 17:04
  • 4
    1) `rand()` is a terrible RNG with no quality guarantees; 2) [the modulo operation introduces bias for most values of `something`](http://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator). http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful – T.C. Feb 15 '15 at 17:08