Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple logic question: check if x is between 2 numbers

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?

like image 956
dukevin Avatar asked Aug 31 '11 06:08

dukevin


People also ask

How do you check if a variable is between two numbers?

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.

How do you check if a number is close to another number in JS?

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.

How do you write a range condition in JavaScript?

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.


2 Answers

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

like image 97
Ray Toal Avatar answered Sep 18 '22 20:09

Ray Toal


Why not just x >= lowerbound && x <= upperbound ?

like image 34
Roland Ewald Avatar answered Sep 16 '22 20:09

Roland Ewald