开发者

Finding if something is within a range programmatically

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 开发者_C百科is inside of the range:

int e = ?;

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


are we talking C here?

(e >= q) && (e <= w)


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 <.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜