0
I’m starting in programming and had enough difficulty to understand If Else in a chained way. I came across the following situation, when running the code only the first or second condition (If/Else) are possible to be true, regardless of the value
float Peso, Altura, Imc;
printf("----------- #17 -----------\n\n");
printf("Para fazer o calculo do IMC, forneca seu peso: \n");
scanf("%f", &Peso);
printf("E sua altura? \n");
scanf("%f", &Altura);
printf("Seu peso e sua altura sao: %.2fKg, %.2fm\n\n",Peso, Altura);
Imc = Peso/(Altura*Altura);
printf("Seu IMC e: %.2f\n", Imc);
if (Imc>=40.0)
{
printf("------------------------------\n");
printf("Voce esta com Obesidade Grau III (morbida)\n");
printf("------------------------------\n");
}
else
{
if(35.0<Imc<39.9)
{
printf("------------------------------\n");
printf("Voce esta com Obesidade Grau II(severa)\n");
printf("------------------------------\n");
}
else
{
if(30.0<Imc<34.9)
{
printf("------------------------------\n");
printf("Voce esta com Obesidade Grau I\n");
printf("------------------------------\n");
}
else
{
if(25.0<Imc<29.9)
{
printf("------------------------------\n");
printf("Voce esta com excesso de peso\n");
printf("------------------------------\n");
}
else
{
if(18.6<Imc<24.9)
{
printf("------------------------------\n");
printf("Voce esta saudavel\n");
printf("------------------------------\n");
}
else
{
if(Imc<18.5)
{
printf("------------------------------\n");
printf("Voce esta abaixo do peso \n");
printf("------------------------------\n");
}
}
}
}
}
}
return 0;
For complementary purposes only, the operator
<
returns the value1
whether the comparison is true, and0
if it is false (see definition here). So,25.0 < Imc < 29.9
is interpreted as "the value of the expression25.0 < Imc
is less than 29.9?". Like the expression25.0 < Imc
can return only 1 or zero, it will always be less than 29.9, so the expression will always be true. I’d forgotten that C had those weird things... :-)– hkotsubo
I will edit and put this, thank you
– Fábio Morais