问题描述
我正在为我的编程课程运行 C 练习,我发现一些计算导致了舍入错误,进而影响了逻辑语句。请看下面代码的最后两行:
if (bmi_result < 18.5)
printf("Your BMI is %.1f and you might be underweight.\n\n",bmi_result);
else if (bmi_result >= 18.5 && bmi_result <= 24.9)
printf("Your BMI is %.1f and you have a normal weight.\n\n",bmi_result);
else if (bmi_result >= 25.0 && bmi_result <= 29.9)
printf("Your BMI is %.1f and you might be overweight.\n\n",bmi_result);
else if (bmi_result >= 30.0)
printf("Your BMI is %.1f and you might be obese.\n\n",bmi_result);
BMI 计算为 double bmi_result = 703 * weight / (height * height);
如果我使用 65(英寸)的身高和 180(磅)的体重,其结果为 29.9502,则 if/else 语句会忽略此值。>
不幸的是,我必须完全按照所写的 BMI 参数进行操作,因为这是此问题的要求。使用 round() 可以解决部分问题(例如,在我给出的特定情况下),但我会在其他值上失去精度。
有没有人对如何解决这个问题有任何建议,并确保程序对任何输入都能准确工作?是否有另一个类似于 round() 的函数允许您指定舍入到特定值(最接近的十分之一)?
解决方法
if (bmi_result < 18.5)
printf("Your BMI is %.1f and you might be underweight.\n\n",bmi_result);
else if (bmi_result >= 18.5 && bmi_result < 25)
printf("Your BMI is %.1f and you have a normal weight.\n\n",bmi_result);
else if (bmi_result >= 25.0 && bmi_result < 30)
printf("Your BMI is %.1f and you might be overweight.\n\n",bmi_result);
else if (bmi_result >= 30.0)
printf("Your BMI is %.1f and you might be obese.\n\n",bmi_result);
试试这种方式,它应该能够捕获 29.9502 值。