0

我正在尝试使用多个条件制作多个 if 语句。如果我运行代码,它可以正常工作,但它永远不会改变输出。我总是得到第二条语句> = 29。这是我的代码。

 if (label.text <= @"30") 
    {label.text = @"Text";}   
else if (label.text >= @"29") 
    {label.text = @"Text";} 
else if (label.text >= @"19")
    {label.text = @"Text";}
else if (label.text >= @"10") 
    {label.text = @"Text";}
else if (label.text  = @"00") 
    {label.text = @"Text";}

好的,我已经更改了我的代码,但我仍然没有任何建议

      label.text = temporaryValue;
     if ([label.text floatValue] <= 30) 
         {label.text = @"text1";}   
else if ([label.text floatValue] >= 29) 
         {label.text = @"text2";}   
else if ([label.text floatValue] >= 19)
         {label.text = @"text3";}
else if ([label.text floatValue] >= 10) 
         {label.text = @"text4";}
else if ([label.text floatValue] == 0) 
         {label.text = @"text5";}
4

3 回答 3

5

你不能像这样比较字符串的数值;此操作执行指针比较,即它比较您传入的字符串实例的(相当随机的)地址。使用如下内容:

if ([label.text floatValue] >= 30.0) {
}

等等

于 2012-07-15T12:48:45.853 回答
1

Using >= or <= with NSString* would compare the addresses, not the content of those strings. If you want to compare like this, you should parse your string into an int and compare it using common integer comparison:

int val = [label.text intValue];
if (val > 30) {
   ...
}
else ... // more of your ifs
于 2012-07-15T12:54:25.593 回答
0

Once you fix your syntax (as suggested in other answers here) you will still have a problem, as once you are dealing with numeric comparisons your logic flow seems flawed. Consider this

if ([label.text floatValue]  <= 30.0) 
    {label.text = @"Text";}   
else if ([label.text floatValue]  >= 29.0) 
    {label.text = @"Text";} 

if your test value IS greater than 30, you move to the next else if

else if ([label.text floatValue]  >= 29.0)

clearly this IS bigger than 29 since it failed to be less than or equal to 30. Therefore all your other conditonals are never reached as assuming your first conditional is false, the second MUST be true.

于 2012-07-15T12:54:21.553 回答