通过Python计算BMI:取2

时间:2012-11-21 00:35:13

标签: python

对我之前的问题感到抱歉。我必须回答的问题是:

身体质量指数(BMI)是大多数人体脂肪的良好指标。 BMI的公式是重量/高度2,其中重量以千克为单位,高度以米为单位。编写一个程序,提示以磅为单位的重量和以英寸为单位的高度,将值转换为公制,然后计算并显示BMI值。

到目前为止我所拥有的是:

"""
BMI Calculator

1. Obtain weight in pounds and height in inches
2. Convert weight to kilograms and height to meters
3. Calculate BMI with the formula weight/height^2
"""

#prompt user for input from keyboard
weight= input ("How much do you weigh (in pounds)?")
#this get's the person's weight in pounds

weight_in_kg= weight/2.2
#this converts weight to kilograms

height= input ("What is your height (in inches)?")
#this gets the person's height in inches

height_in_meter=height*2.54
#this converts height to meters

bmi=weight_in_kg/(height_in_meters*2)
#this calculates BMI

print (BMI)

我的第一步有效,但这很容易。我知道在Python中等号会分配一些东西,所以我不确定这是不是问题,但我真的不知道该怎么办。真的对不起。当我运行该程序时,它说:

TypeError:/:'str'和'float'

的不支持的操作数类型

如果有人能给我任何关于我做错的提示,我会非常感激。如果没有,谢谢你的时间。再次感谢。

4 个答案:

答案 0 :(得分:4)

对于Python 3.x(指定):

问题是来自input()的键盘输入是str(字符串)类型,它不是数字类型(即使用户输入数字)。但是,通过更改输入行可以很容易地解决这个问题:

weight = float(input("How much do you weigh (in pounds)?"))

height = float(input("What is your height (in inches)?"))

因此将input()的字符串输出转换为数字float类型。

答案 1 :(得分:2)

首先,有一个拼写错误:height_in_meter(S)。 对于Python 2,不需要前面的float(...,但我确信这是一个好习惯。

"""
BMI Calculator

1. Obtain weight in pounds and height in inches
2. Convert weight to kilograms and height to meters
3. Calculate BMI with the formula weight/height^2
"""

#prompt user for input from keyboard
weight= input ("How much do you weigh (in pounds)?")
#this get's the person's weight in pounds

weight_in_kg= weight/2.2
#this converts weight to kilograms

height= input ("What is your height (in inches)?")
#this gets the person's height in inches

height_in_meter=height*2.54/100
#this converts height to centimeters

bmi=weight_in_kg/(height_in_meter**2)
#this calculates BMI

print (bmi)

答案 2 :(得分:0)

weight= float(input("How much do you weigh (in kg)?"))
weight_in_kg= float(input("Enter weight in kg?"))


#height= float(input("What is your height (in meters)?"))
height_in_meter= float(input("Enter height in metres?"))


bmi=weight_in_kg/(height_in_meter**2)


print (bmi)

我发现这是最简单的方法,希望这有帮助

答案 3 :(得分:0)

# height and weight are available as a regular lists

# Import numpy
import numpy as np

# Create array from height with correct units: np_height_m
np_height_m = np.array(height) * 0.0254

# Create array from weight with correct units: np_weight_kg 
np_weight_kg = np.array(weight) * 0.453592

# Calculate the BMI: bmi
bmi =  np_weight_kg / (np_height_m **2)

# Print out bmi
print(bmi)