iOS Objective C使用if语句编写Xcode

时间:2014-07-24 22:19:12

标签: ios objective-c

所以我试图在应用程序中使用if语句来计算人体重指数(BMI)。 我需要用户能够输入公制或英制单位的重量和高度,我真的希望能够让用户输入公制重量,例如英制高度​​。 我认为使用if语句是最好的,我的代码在下面。目前我对if语句有警告,它只是忽略它们。非常感谢任何帮助。

- (IBAction)calculateProcess:(id)sender {
    float cm = [_cmHeight.text floatValue];
    float feet = [_feetHeight.text floatValue];
    float inches = [_inchesHeight.text floatValue];
    float kg = [_kgWeight.text floatValue];
    float stone = [_stoneWeight.text floatValue];
    float pound = [_poundWeight.text floatValue];
    float height;
    float mass;

    if (cm == 0){
        float height = 0.3048*feet + 0.0254*inches;
    } else {
        float height = cm/100;
    }

    if (kg == 0){
        float mass = (6.35029*stone) + (0.453592*pound);
    } else {
        float mass = cm/100;
    }

    float bmi = mass/(height*height);
    [_resultLabel setText:[NSString stringWithFormat:@"%.2f", bmi]];
}

1 个答案:

答案 0 :(得分:0)

if-else块重新声明堆栈变量heightmass,因此if-else块之后的代码将看不到条件结果。改变这种方式......

// ...
float height;
float mass;

if (cm == 0){
    // see - no float type
    height = 0.3048*feet + 0.0254*inches;
} else {
    height = cm/100;
}

if (kg == 0){
    mass = (6.35029*stone) + (0.453592*pound);
} else {
    mass = cm/100;
}

顺便说一下,这两个陈述可以更加简洁:

height = (cm == 0)? 0.3048*feet + 0.0254*inches : cm/100;
mass = (kg == 0)? (6.35029*stone) + (0.453592*pound) :  cm/100;