You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ BMI计算器if else判断失效:string比较始终触发第一个分支

问题根因

你的条件判断逻辑存在语法错误:C++中逻辑或||运算符两侧是独立的布尔判断单元,你写的measurementSystem == "metric" || "Metric" 里,右侧的"Metric"是字符串字面量,会被隐式转换为布尔值true,因此整个if条件的结果永远为真,不管输入什么内容都会进入第一个分支。

修正方案
  • 把两个分支的条件都补全为完整的等式判断:
    第一个if条件改为 if (measurementSystem == "metric" || measurementSystem == "Metric")
    第二个else if条件改为 else if (measurementSystem == "english" || measurementSystem == "English")
  • 额外优化建议:
    1. 公制下身高单位是米,通常会有小数输入,把height和weight的类型从int改为double,避免整数截断导致后续BMI计算错误
    2. system("pause>0")仅适配Windows平台,如果需要跨平台运行可以替换为标准输入等待逻辑
修正后完整代码
#include <iostream>
using namespace std;

int main()
{
    double weight;
    double height;
    string measurementSystem;

    cout << "Metric or English?: \n";
    cin >> measurementSystem;

    if (measurementSystem == "metric" || measurementSystem == "Metric") {
        cout << "Enter your weight (kg): \n";
        cin >> weight;
        cout << "Enter your height (m): \n";
        cin >> height;
    } else if (measurementSystem == "english" || measurementSystem == "English") {
        cout << "Enter your weight (lbs): \n";
        cin >> weight;
        cout << "Enter your height (in): \n";
        cin >> height;
    } else {
        cout << "Please check spelling";
    }
    
    system("pause>0");
    return 0;
}

内容的提问来源于stack exchange,提问作者user16906235

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 15:21:00