#!/usr/bin/env python3 """BMI 计算器:输入身高(cm)与体重(kg),输出 BMI 与健康分级。""" from dataclasses import dataclass # ---------- 分级标准 ---------- # 中国成人标准 (WS/T 428-2013) CHINA_STANDARD = [ (18.5, "偏瘦"), (24.0, "正常"), (28.0, "超重"), (float("inf"), "肥胖"), ] # WHO 国际标准 WHO_STANDARD = [ (18.5, "Underweight"), (25.0, "Normal"), (30.0, "Overweight"), (float("inf"), "Obese"), ] def calc_bmi(height_cm: float, weight_kg: float) -> float: """BMI = 体重(kg) / 身高(m)^2""" if height_cm <= 0 or weight_kg <= 0: raise ValueError("身高和体重必须为正数") height_m = height_cm / 100 return weight_kg / (height_m ** 2) def classify(bmi: float, standard: list) -> str: """按给定标准表返回分级名称。""" for upper, label in standard: if bmi < upper: return label raise AssertionError("unreachable") @dataclass class Result: bmi: float china: str # 中国标准分级 who: str # WHO 标准分级 normal_low_kg: float # 中国"正常"下限对应体重 normal_high_kg: float # 中国"正常"上限对应体重 def analyze(height_cm: float, weight_kg: float) -> Result: """一次给出 BMI、两套分级,以及正常体重范围。""" bmi = calc_bmi(height_cm, weight_kg) h2 = (height_cm / 100) ** 2 return Result( bmi=bmi, china=classify(bmi, CHINA_STANDARD), who=classify(bmi, WHO_STANDARD), normal_low_kg=18.5 * h2, normal_high_kg=23.9 * h2, ) def main(): try: height = float(input("请输入身高(cm): ")) weight = float(input("请输入体重(kg): ")) except ValueError: print("输入无效:请输入数字,例如 181 和 60。") return try: r = analyze(height, weight) except ValueError as e: print(f"输入错误:{e}") return print(f"\n身高 {height:.1f} cm | 体重 {weight:.1f} kg") print(f"BMI : {r.bmi:.2f}") print(f"分级 : {r.china} (中国标准)") print(f" {r.who} (WHO 标准)") print(f"正常体重范围: {r.normal_low_kg:.1f} ~ {r.normal_high_kg:.1f} kg") if __name__ == "__main__": main()