简单的逻辑问题:检查 x 是否在 2 个数字之间 [英] simple logic question: check if x is between 2 numbers
问题描述
我想看看一个变量是否在一个值范围内,例如如果 x 在 20 和 30 之间返回 true.
I want to see if a variable is between a range of values, for example if x is between 20 and 30 return true.
最快的方法是什么(使用任何基于 C 的语言)?
What's the quickest way to do this (with any C based language)?
显然可以通过 for 循环来完成:
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
但是做起来很麻烦 if(inRange(x, 20, 30))
有没有比这更简单的逻辑不使用内置函数?
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?
推荐答案
你要的表达式是
20 <= x && x <= 30
或者干脆放在一个函数里
Or simply put in in a function
function inRange(x, lowerbound, upperbound)
{
return lowerbound <= x && x <= upperbound;
}
Python 有一个 in
运算符:
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
在 Python 中也是如此,这很酷——比较运算符是链式的!这与 C 和 Java 完全不同.请参阅 http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Comparison_operators
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
所以你可以写
low <= x <= high
在 Python 中 -10 <= -5 <= -1
为真,但在 C 中为假.试试看.:)
In Python -10 <= -5 <= -1
is True, but in C it would be false. Try it. :)
这篇关于简单的逻辑问题:检查 x 是否在 2 个数字之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!