这是我的部分代码:
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/