通过Python计算BMI:取2

2024-05-15 15:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

对我之前的问题很抱歉。我要回答的问题是:

体重指数(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”的操作数类型

如果有人能告诉我我做错了什么,我会非常感激的。如果没有,谢谢你抽出时间。再次感谢。


Tags: thetoin程序input单位指数this
3条回答

首先,有一个输入错误: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)
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)

我发现这是最简单的方法,希望能帮上忙

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

相关问题 更多 >