Search code examples
coperatorscomparison-operators

Chaining of Relational operators is giving wrong output


Can anyone explain this to me? Did I do something wrong? When I run the program it doesn't show me the right answer.

ex : when I type weight = 50 kg and height = 130 cm the answer should be

"Your BMI is 29.58. You are overweight2.You will have a chance to cause high blood pressure and diabetes need to control diet. And fitness."

but the answer that shows is

"Your BMI is 29.58. You are normal......"


#include<stdio.h>
#include<conio.h>

int main() {
  float weight, height, bmi;

  printf("\nWelcome to program");

  printf("\nPlease enter your weight(kg) :");
  scanf("%f", &weight);

  printf("\nPlease enter your height(cm) :");
  scanf("%f", &height);

  bmi=weight/((height/100)*(height/100));

  if(bmi<18.50) { 
    printf("Your bmi is : %.2f",bmi);
    printf("You are Underweight.You should eat quality food and a sufficient amount of energy and exercise proper.");
  } else if(18.5<=bmi<23) {
    printf("Your bmi is : %.2f \nYou are normal.You should eat quality food and exercise proper.",bmi);
  } else if(23<=bmi<25) {
    printf("Your bmi is : %.2f \nYou are overweight1 if you have diabetes or high cholesterol,You should lose weight body mass index less than 23. ",bmi);
  } else if(25<=bmi<30) {
    printf("Your bmi is : %.2f \nYou are overweight2.You will have a chance to cause high blood pressure and diabetes need to control diet. And fitness.",bmi);
  } else if(bmi>=30) {
    printf("Your bmi is : %.2f \nYou are Obesity.Your risk of diseases that accompany obesity.you run the risk of highly pathogenic. You have to control food And serious fitness.",bmi);
  } else {
    printf(" Please try again! ");
  }

  return 0;
  getch();
}

Solution

  • In your code, what you've tried

     else if(18.5<=bmi<23)
    

    No, this kind of chaining of Relational operators is not possible in C. You should write

     else if((18.5<=bmi) &&  (bmi < 23))
    

    to check bmi value in [18.5, 23) and so on for the other cases.


    EDIT:

    Just to elaborate about the issue, an expression like

    18.5<=bmi<23
    

    is perfectly valid C syntax. However, it is essentially the same as

    ((18.5<=bmi) < 23 )
    

    due to the operator associativity.

    So, first the (18.5<=bmi) is evaluated and the result , (0 or 1) gets to get comapred against 23, which is certainly not you want here.