python - 浮点计算和控制流

标签 python floating-point

这是我的部分代码:

students = 0
weight = 0
height = 0

while students < 5:
    name = input("Please enter the name. ")
    students = students + 1

while weight == 0:
    try:
        weight = float(input("Please enter the weight in kgs "))

        if weight <= 0:
            print ("Please enter a number greater than zero ")
            weight = 0
            continue

    except ValueError:
        print ("No number found, please enter a number greater than zero ")
        weight = 0
        continue

while height == 0:
    try:
        height = float(input("Please enter the height in metres "))


        if height <= 0:
            print ("Please enter a number greater than zero ")
            height = 0
            continue

    except ValueError:
        print ("No number found, please enter a number greater than zero ")
        height = 0
        continue

BMI = (weight/(height*height))
print (name, "has the BMI of", "%.2f" %BMI)
if BMI < 18.5:
    print ("The student is underweight.")
elif 18.5 <= BMI <= 27:
    print ("The student is a healthy weight.")
elif BMI > 27:
    print ("The student is overweight.")

weight = 0
height = 0

但是,当 BMI 为 18.5 时,表示该学生体重不足,而当 BMI 为 27 时,则表示该学生超重,两者实际上应该是健康体重? 例如体重53.456,高度1.7m显示偏瘦

最佳答案

>>> 53.456/(1.7*1.7)
18.496885813148793
>>> 53.456/(1.7*1.7) <= 18
False

在我看来它只是浮点错误,试试

>>> round(53.456/(1.7*1.7), 2)
18.5
>>> round(53.456/(1.7*1.7), 2) <= 18.5
True

future 的问题解决策略:每当事情看起来不太对劲时,打开 python shell 并稍微弄乱一下,您可能会自己找到解决方案。

关于python - 浮点计算和控制流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25539910/

相关文章:

python - 如何使用python识别中文或英文名字

floating-point - 如何获取包含 float 的迭代器的最小值或最大值?

python - 如何将 ndarray 字符串列表转换为 float

math - 稍微转向浮点 (im) 精度,第 1 部分

matlab - Matlab 中的非运算符行为异常

c - 如何在 C 中表示内存中的 FLOAT 数

python - 是否有与 `unittest.TestCase.fail()` 相反的方法来通过 Python 单元测试?

python - 使用 Python 对抓取数据进行编码

python - 在满足峰值的地方分割数组

python - 确定 TD 标签内的类