if else statement problem

Hi. I'm having a problem. So I'm making a BMI calculator and everytime I type whatever value, it display 'normal'. Why is this hapenning? Beginner here. i'll show the part of the code which I find its false.

1
2
3
4
5
6
7
8
9
if (BMI <= 18.5)
  cout <<"Situation: Underweight "<< myadvice1.getBMIadvice() << endl;
 else if (BMI >= 18.5 )
  cout <<"Situation: Normalweight "<<myadvice2.getBMIadvice()<<endl;
 else if (BMI >=25)
  cout<<"Situation: Overweight "<< myadvice3.getBMIadvice()<<endl;
 else if (BMI >= 30)
  cout<<"Situation: Obese "<< myadvice4.getBMIadvice()<<endl;
}
BMI <= 18.5 should work fine.

The problem at line 3 is that any BMI >= 18.5 will result in the if statement being true and none of the remaining if statements will be evaluated.

Since normal range is 18.5 - 25, your if statement needs to reflect that.
1
2
 
else if (BMI >= 18.5 && BMI < 25)


Likewise for the next condition.
 
else if (BMI >=25 && BMI < 30)


You don't need an if statement for the last else, since BMI can't be anything other than >= 30.
1
2
else 
  cout<<"Situation: Obese "<< myadvice4.getBMIadvice()<<endl;

Do not duplicate conditions. Code duplication is bad.

The 'else' already ensures that previous 'if' conditions are false, you do not (and should not) repeat those conditions.

1
2
3
4
5
6
7
// BAD -- don't do this!
if (BMI <= 18.5)
    //...
else if (BMI > 18.5 && BMI < 25)
    //...
else if (BMI >=25 && BMI < 30)
    //... 

1
2
3
4
5
6
7
//better:
if(BMI <= 18.5)
    //...
else if(BMI < 25)  // because of the 'else', we already know BMI is > 18.5.  No need to check again
    //...
else if(BMI < 30)  // again, because of the 'else', we know BMI >= 25
    //... 



EDIT:
the original problem was because your conditions were formed poorly:

1
2
3
4
5
6
7
8
if (BMI <= 18.5)
    // this covers BMI <= 18.5
else if (BMI >= 18.5 )
    // and this covers BMI >= 18.5
  // those 2 conditions cover EVERY POSSIBLE value for BMI
else if(BMI >= 25)
    // so this will never execute, because if BMI is >= 25, it's also >= 18.5, so the
    //  previous 'if' block would have executed 
Last edited on
Topic archived. No new replies allowed.