100< = x< = 150作为if()中的参数,很有趣 [英] 100 <= x <= 150 as argument in if (), acting funny
问题描述
我有一个 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不能时为什么它不会继续到下一个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
推荐答案
您需要重新声明以下语句:
You need to rephrase the statements like:
if (x >= 100 && x <= 149) {
} else if (x >= 150 && x <= 199) {
} ...
您的第一个如果
的计算方式如下:
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 value1
(which means true). And then1 <= 149
is also true. - If
x
has a value smaller than 100, for example10
, then(100 <= 10)
is false and thus evaluates to the value0
(which means false). Again,0 <= 149
is true.
因此,无论值 x
,整个表达式将始终为真。
So regardless of the value of x
, the whole expression will always be true.
这篇关于100< = x< = 150作为if()中的参数,很有趣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!