【深基3.例7】肥胖问题 · 教师题解

【深基3.例7】肥胖问题

解题思路

用 double 计算 BMI=m/(h*h)。小于 18.5 输出 Underweight,否则小于 24 输出 Normal,剩下先输出 BMI 再输出 Overweight。

正确性说明

按从小到大判断得到互不重叠的三个区间,恰好覆盖全部可能的 BMI。

易错点

只有肥胖分支打印 BMI;使用 cout 默认六位有效数字,不设置 fixed。

复杂度

时间 O(1),空间 O(1)。

参考代码(C++11)

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    double m, h;
    cin >> m >> h;
    double bmi = m / (h * h);
    if (bmi < 18.5)
        cout << "Underweight\n";
    else if (bmi < 24)
        cout << "Normal\n";
    else
        cout << bmi << "\nOverweight\n";
    return 0;
}
返回题目