【问题标题】:There is something wrong with my calculations in python [duplicate]我在 python 中的计算有问题 [重复]
【发布时间】:2017-11-03 10:13:52
【问题描述】:

我正在尝试学习 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?怎么了?

【问题讨论】:

  • 您使用的是 Python 2,我猜?除非您病态肥胖,否则height 将大于weight,因此根据 dup,答案将为零。
  • 改变这一行 BMI = (体重/身高 ** 2) * float(10000)
  • 更好的 BMI = (体重/浮动(身高) ** 2) * 10000

标签: python


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多