Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 views
in Technique[技术] by (71.8m points)

objective c - 100 <= x <= 150 as argument in if (), acting funny

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  • 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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...