浮点计算和控制流程

时间:2014-08-28 02:42:57

标签: 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.7米显示体重不足

3 个答案:

答案 0 :(得分:2)

>>> 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

未来的问题解决策略:每当某些事情看起来并不正确时,破解python shell并稍微乱一点,你可能会自己找到解决方案。

答案 1 :(得分:0)

一般来说,浮点数不准确,因为它们在计算机中的表现方式。它们只是非常接近的近似值。因此,测试与浮点数的精确相等必然会导致挫败感。您可能应该关闭数字或不测试相等性。

如果你有兴趣进一步探索,那么timrau发布的链接实际上是一个非常好的介绍。

答案 2 :(得分:0)

浮点数仅近似十进制数。你的比较可能会超过/低于你的乘法或除法的顺序或一天的时间......不完全。如果您想要进行有意义的相等比较,那么请查看python中的decimal库。您可以将精度设置为两位小数,突然您的比较和计算器数学应该有效。