问题
I want to see if a variable is between a range of values, for example if x is between 20 and 30 return true.
What's the quickest way to do this (with any C based language)?
It can obviously be done with a for loop:
function inRange(x, lowerbound, upperbound)
{
for(i = lowerbound; i < upperbound; i++)
{
if(x == i) return TRUE;
else return FALSE;
}
}
//in the program
if(inRange(x, 20, 30))
//do stuff
but it's awful tedious to do if(inRange(x, 20, 30))
is there simpler logic than this that doesn't use built in functions?
回答1:
The expression you want is
20 <= x && x <= 30
EDIT:
Or simply put in in a function
function inRange(x, lowerbound, upperbound)
{
return lowerbound <= x && x <= upperbound;
}
Python has an in
operator:
>>> r = range(20, 31)
>>> 19 in r
False
>>> 20 in r
True
>>> 30 in r
True
>>> 31 in r
False
Also in Python, and this is pretty cool -- comparison operators are chained! This is totally unlike C and Java. See http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Comparison_operators
So you can write
low <= x <= high
In Python -10 <= -5 <= -1
is True, but in C it would be false. Try it. :)
回答2:
Why not just x >= lowerbound && x <= upperbound
?
来源:https://stackoverflow.com/questions/7253261/simple-logic-question-check-if-x-is-between-2-numbers