如何将BMI计算添加到以下代码中?

时间:2016-03-27 00:45:10

标签: jython jes

下面是我的代码:

def inForm():
  name = requestString("What is your name?")
  age = requestInteger("What is your age?")
  height = requestInteger("What is your height?")
  weight = requestInteger("What is your weight?")
  print "Hello", name, "!", "You are", age,"years old!", "Your height  
  is", height, "cm", "and you weigh", weight, "kg"

我需要将BMI计算添加到此代码中,这是我的公式,BMI =体重/(身高*身高)

根据BMI显示这些消息:

你的体重低于15

你的体重严重不足15.0至16.0

你的体重从16.0降至18.5

你的体重正常,从18.5到25

你超重25到30

你从30岁到35岁是中度肥胖

你从35岁到40岁严重肥胖

你是40岁以上非常严重的肥胖

我似乎无法弄明白,我怎么会这样做?

提前致谢!

2 个答案:

答案 0 :(得分:0)

为了计算bmi,通常使用以米为单位的高度(而不是cm)。这意味着您需要在公式中从cm到m的转换调整两次:

bmi = 10000 * weight / (height*height)
print bmi

您可以对文本部分使用if-elif -...- else语句:

if bmi < 15:
    message = "very severely underweight"
elif bmi <= 16:
    message = "severely underweight"
# Add more elif parts here...
else:
    message = "very severely obese"

print "You are", message

答案 1 :(得分:0)

为什么不使用requestNumber作为身高和体重,而不是从cm转换为m。此外,print语句可能会更短,就像我在下面演示的那样。另外,我使用%s%d%r这称为String Formatting Operations

def inForm():
 name = requestString("Please enter your name")
 age = requestInteger("How old are you?")
 height = requestNumber("How tall are you? (Meters)")
 weight = requestNumber("How heavy are you? (Kilograms)")
 bmi = weight/(height*height)

 print "Hello, %s! I see that you are %r years old, %r meters tall, weight %r kgs and your BMI is %d." % (name, age, height, weight, bmi)

 n = bmi
 if n<15:
  print "You are very severely underweight"
 elif 15<=n<=16:
  print "You are severely underweight"
 elif 16<n<=18.5:
  print "You are underweight"
 elif 18.5<n<=25:
  print "Your weight is normal"
 elif 25<n<=30:
  print "You are overweight"
 elif 30<n<=35:
  print "You are moderately obese"
 elif 35<n<=40:
  print "You are severely obese"
 elif n>40:
  print "You are very severely obese"