我有一些Objective C,我不理解变量比较运算符:
if ([bmiView.text floatValue] < 18.50) {
classification.text = @"Underweight";
bmiImageView.image = [UIImage imageNamed:@"underweight.png"];
}
if ([bmiView.text floatValue] > 18.50 < 24.99) {
classification.text = @"Healthy";
bmiImageView.image = [UIImage imageNamed:@"healthy.png"];
}
if ([bmiView.text floatValue] > 25 < 29.99) {
classification.text = @"Overweight";
bmiImageView.image = [UIImage imageNamed:@"overweight.png"];
}
if ([bmiView.text floatValue] > 30 < 39.99) {
classification.text = @"Obese";
bmiImageView.image = [UIImage imageNamed:@"obese.png"];
}
if ([bmiView.text floatValue] > 40) {
classification.text = @"Very Obese";
bmiImageView.image = [UIImage imageNamed:@"veryobese.png"];
}
每次运行应用程序时,当用户的BMI超过40.00时,唯一正常工作的分类是“非常肥胖”。任何其他BMI导致下面的分类,“Obese”,这应该是30.00和39.99之间的BMI。为什么不起作用?
答案 0 :(得分:3)
if ([bmiView.text floatValue] > 18.50 < 24.99) {
......没有按照你的想法去做。你需要做两次比较;
if ([bmiView.text floatValue] > 18.50 && [bmiView.text floatValue] < 24.99) {
另请注意,如果浮点值完全 25,则不会出现任何情况。
使用else
重写代码可能是一个好主意,因此您可以跳过检查下限;
if ([bmiView.text floatValue] < 18.50) {
classification.text = @"Underweight";
bmiImageView.image = [UIImage imageNamed:@"underweight.png"];
}
else if ([bmiView.text floatValue] < 25.0) {
classification.text = @"Healthy";
bmiImageView.image = [UIImage imageNamed:@"healthy.png"];
}
...
旁注,[bmiView.text floatValue] > 18.50 < 24.99
做的是将floatvalue与18.5
进行比较,结果产生1或0,具体取决于它是真还是假。然后继续比较0/1是否小于24.99,这总是正确的。
答案 1 :(得分:0)
看起来您的比较应该更像:
if ([bmiView.text floatValue] > 25 && [bmiView.text floatValue] < 29.99) {
classification.text = @"Overweight";
bmiImageView.image = [UIImage imageNamed:@"overweight.png"];
}