100 <= x <= 150 作为 if () 中的参数,表现得很有趣 [英] 100 <= x <= 150 as argument in if (), acting funny

查看:44
本文介绍了100 <= x <= 150 作为 if () 中的参数,表现得很有趣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 if 语句,后跟几个 else if 语句.所有 if/else if 语句都有一个结构如下的参数:

I have an if statement followed by several else if statements. All of the if/else if statements have an argument structured something like this:

if (100 <= x <= 149) //do this
else if (150 <= x <= 199) //do that
else if ...etc...

但是,由于某种原因,只有第一个 if 语句才会被执行.X 可以是 200,并且只会识别第一个 if 语句.

However, for some reason only the first if statement ever gets executed. X can be 200 and only the first if statement will be recognized.

我不知道为什么当 X 不符合前一个语句的参数时,它没有转到下一个 else if 语句.这在 Obj-C 中不起作用吗?任何帮助表示赞赏.谢谢

I'm not sure why it isn't moving on to the next else if statement when X doesn't fit the argument of the preceding statement. Does this not work in Obj-C? Any help is appreciated. Thanks

推荐答案

你需要改写如下语句:

if (x >= 100 && x <= 149) {
} else if (x >= 150 && x <= 199) {
} ...

你的第一个 if 被评估为:

Your first if is evaluated like:

if ((100 <= x) <= 149)

让我们看看它是如何评估的:

Let's have a look how that evaluates:

  • 如果 x = 200,则 (100 <= 200) 为真,因此计算结果为值 1(表示真).然后 1 <= 149 也是如此.
  • 如果 x 的值小于 100,例如 10,则 (100 <= 10) 为假,因此计算到值 0 (这意味着 false).同样,0 <= 149 为真.
  • If x = 200, then (100 <= 200) is true and thus evaluates to the value 1 (which means true). And then 1 <= 149 is also true.
  • If x has a value smaller than 100, for example 10, then (100 <= 10) is false and thus evaluates to the value 0 (which means false). Again, 0 <= 149 is true.

所以不管 x 的值如何,整个表达式总是为真.

So regardless of the value of x, the whole expression will always be true.

这篇关于100 &lt;= x &lt;= 150 作为 if () 中的参数,表现得很有趣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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