当我输入超过 18.5 的值时,它表示正常,但一切正常。如何设置 If 和 Else 语句?
我是 C 在线类(class)的学生,我必须编写一个程序来计算某人的 BMI 并显示他们是否“正常”、“超重”等。
//Clear the screen
system("clear");
//Declare variables
float weight, height, bmi;
int number_of_inputs = 2; //Interger constant or literal
//Get grades from user
printf("Please enter Weight in Pounds: ");
scanf("%f", &weight);
printf("Please enter your Height in inches: ");
scanf("%f", &height);
//Calculate the BMI
bmi = 703 * (weight / (height * height) );
//Display what is the health status of the user
if (bmi >= 18.5 <= 24)
{
printf("Your Health Status is Normal \n");
}
else if (bmi <= 18.5 >= 0)
{
printf("Your Health Status is Underweight \n");
}
else if (bmi >= 25 <= 29)
{
printf("Your Health Status is Overweight \n");
}
else if (bmi >= 30 <= 999)
{
printf("Your Health Status is Obese \n");
}
printf("BMI: %f \n", bmi);
return (0);
任何超过 18.5 的值都不会打印正确的 If/Else 语句,但低于 18.5 的任何值都会打印出正确的 If/Else 语句
最佳答案
类似这样的表达式:
bmi >= 18.5 <= 24
它不做你认为它做的事。应该写成:
bmi >= 18.5 && bmi <= 24
<小时/>
更详细地说,错误表达式的处理方式类似于(1):
(bmi >= 18.5) <= 24
其中 bmi >= 18.5
为您提供一个 true/false
值,表示为 1/0
。然后使用此 1
或 0
与 24
进行比较,这就是为什么您似乎会得到奇怪的结果。
事实上,您实际上并不需要检查范围的两端,因为可能性涵盖了整个输入值集。我会建议类似的东西(排除常见的东西):
printf("Your health status is ");
if (bmi <= 18.5) puts("underweight"); // [-inf, 18.5]
else if (bmi <= 24.0) puts("normal"); // (18.5, 24.0]
else puts("overweight"); // (24.0, +inf]
<小时/>
(1) 我说“类似”,因为这取决于评估顺序,而我现在懒得去查找。首先,它只是决定您会看到哪些可能的奇怪行为,其次,如果您使用正确的表达式,您就不需要担心它:-)
关于c - 如果我的数字变量超过特定值,则 if 和 else 语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54567775/