简单的逻辑问题:检查x是否在2个数字之间 [英] simple logic question: check if x is between 2 numbers

查看:103
本文介绍了简单的逻辑问题:检查x是否在2个数字之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查看变量是否介于一定范围的值之间,例如,如果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

但如果(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

编辑:

或者只是放入函数

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 是True,但在C中它是false。尝试一下。 :)

In Python -10 <= -5 <= -1 is True, but in C it would be false. Try it. :)

这篇关于简单的逻辑问题:检查x是否在2个数字之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆