1

In my program, I have to find two random values with certain conditions:

i needs to be int range [2...n]

k needs to be in range [i+2...n]

so I did this:

i = rand() % n + 2;
k = rand() % n + (i+2);

But it keeps giving me wrong values like

for n = 7

I get i = 4 and k = 11

or i = 3 and k = 8

How can I fix this?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Meryem
  • 477
  • 7
  • 17

2 Answers2

2

The exact formula that I use in my other program is:

i = min + (rand() % (int)(max - min + 1))

Look here for other explanation

Ian Gallegos
  • 524
  • 1
  • 9
  • 18
1

As the comments say, your range math is off.

You might find it useful to use a function to work the math out consistently each time. e.g.:

int RandInRange(int x0, int x1)
{
    if(x1<=x0) return x0;
    return rand() % (x1-x0+1) + x0;
}

then call it with what you want:

i = RandInRange(2,n);
k = RandInRange(i+2,n);
L. Scott Johnson
  • 4,213
  • 2
  • 17
  • 28