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?
To check if a number is between two numbers: Use the && (and) operator to chain two conditions. In the first condition check that the number is greater than the lower range and in the second, that the number is lower than the higher range. If both conditions are met, the number is in the range.
First we need to know how to get the difference between 2 numbers in JavaScript. The easiest way to do this is to use Math. abs(), so lets use that. With this function we check whether the absolute value of (b – 8) is less than the absolute value of (a – 8) and then return the winner.
function numbers_ranges(x, y) { if ((x >= 40 && x <= 60 && y >= 40 && y <= 60) || (x >= 70 && x <= 100 && y >= 70 && y <= 100)) { return true; } else { return false; } } console.
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. :)
Why not just x >= lowerbound && x <= upperbound
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With