我在python中的计算有问题

时间:2017-06-02 05:34:37

标签: python

我正在尝试学习python,作为测试我试图制作BMI计算器

#BMI Calculator

name = raw_input ("What is your name?: ")
weight = raw_input ("Hello %s What is your weight? (kilo): "% (name))
height = raw_input ("And what is your height? (cm) ")

#Calculations: weight / height^2 * 10000

weight = int(weight)
height = int(height)

BMI = (weight / height ** 2) * 10000

print "%s, your BMI is %s"% (name, BMI)

但是计算似乎有问题,因为我总是以BMI为0?怎么了?

1 个答案:

答案 0 :(得分:2)

在Python和几种语言中/是“整数除法”的运算符。例如,在Python中,尝试:

num = 1 / 2 # Comes out to be 0

相反,请确保您的除法计算中涉及的数字之一是浮点数:

num = 1.0 / 2 # Comes out to be 0.5!

在您的方案中,由于heightweight是整数,因此意外进行整数除法!

您也可以将变量转换为浮点数,如下所示:

weight_f = float(weight)