Meryem
Meryem

Reputation: 487

rand() in range returning numbers outside of the range

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?

Upvotes: 1

Views: 240

Answers (2)

Ian Gallegos
Ian Gallegos

Reputation: 558

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

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

Look here for other explanation

Upvotes: 2

L. Scott Johnson
L. Scott Johnson

Reputation: 4412

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

Upvotes: 1

Related Questions