tags:

views:

86

answers:

3

I know this is a simple math problem but for some reason im drawing a blank.

If I have two ints which are boundaries for a range:

int q = 100;
int w = 230;

and then another in that is a number that I want to see if it is inside of the range:

int e = ?;

How can I find if e is in the bounds of q and w?

+6  A: 

are we talking C here?

(e >= q) && (e <= w)
darren
Haha that could work, I guess I was thinking to hard. I was trying some crazy things...
Jacob Nelson
happens to the best of us :)
darren
After looking at the other answers, you probably should make clear your assumptions about q and w. Which one is smaller / larger etc.
darren
+3  A: 

First you need to find which of q and w is your lower bound and which is your upper bound.

int upper, lower;

if (q <= w) {
    lower = q;
    upper = w;
} else {
    lower = w; 
    upper = q;
}

Then you just perform a simple test

if (lower <= e) && (e <= upper) {
     // e is within the range
} else {
     // e is outside the range
}

This assumes that you want the range to include q and w. Otherwise, replace <= with <.

aaronasterling
A: 

For some obfuscation:

#define IN_RANGE(q,w,e) (((q > w ? q : w) > e) && ((q < w ? q : w) < e)) ? 1 : 0 

Before you start talking about how terrible defines are, this is just a "simple" example.

muntoo