简体   繁体   中英

iOS Objective C Programming Xcode using if statements

So I am trying to use if statements in an app to calculate a persons body mass index (BMI). I needs the user to be able to input either metric or imperial units for weight and height and I would really like to be able to have the user even input metric weight for example, and imperial height. I thought using an if statement would be best and my code is below. Currently I have warnings on the if statements and it just ignores them. Many thanks to any help.

- (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]];
}

The if-else blocks redeclare the stack variables height and mass , so the code after the if-else blocks won't see the conditional results. Change this way ...

// ...
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;
}

As an aside, both statements can be made more concise like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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