繁体   English   中英

使用if语句的iOS Objective C编程Xcode

[英]iOS Objective C Programming Xcode using if statements

因此,我尝试在应用程序中使用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]];
}

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM