Reputation: 3006
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
?
Upvotes: 1
Views: 195
Reputation: 27201
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.
Upvotes: 0
Reputation: 70994
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 <
.
Upvotes: 3