这是我用输入和运算计算BMI的代码,以下结构和公式是否正确?

2024-09-28 22:29:03 发布

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

#input
name = input("Enter your name:")
height = input ("Height:")
weight = input ("Weight:")
print("Weight:" + weight +"kg")
print("height:" + height +"m")
print("My name is " + name +"!")

#operations with decimal numbers
metres = float(height)
height_sqr =  pow(metres,2)

kg = float(weight)
BMI = float(kg)/height_sqr

#print BMI results
print("BMI:" +str(BMI) +"Kg/M2")

Tags: nameinputyourmyfloatprintbmienter
1条回答
网友
1楼 · 发布于 2024-09-28 22:29:03

如果您想要一个更优化的方法,这里是:

# getting input from the user and assigning it to the user

height = float(input("Enter height in meters: "))
weight = float(input("Enter weight in kg: "))

# the formula for calculating bmi

bmi = weight/(height**2) 
# ** is the power of operator i.e height*height in this case

print("Your BMI is: {0} and you are: ".format(bmi), end='')

#conditions
if ( bmi < 16):
   print("severely underweight")

elif ( bmi >= 16 and bmi < 18.5):
   print("underweight")

elif ( bmi >= 18.5 and bmi < 25):
   print("Healthy")

elif ( bmi >= 25 and bmi < 30):
   print("overweight")

elif ( bmi >=30):
   print("severely overweight") 

在这里,您既不必将输入作为字符串,然后将其转换为浮点,也不必使用函数来计算幂。 它还显示了你的体重指数的范围

代码的效率是一样的

相关问题 更多 >