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

BMI计算器条件判断失效:BMI<18.5时控制台未输出预期内容

BMI计算器条件判断失效问题修复

问题原因

  • 直接拿函数对象bmiCalculator和数值18.5做比较:函数本身是引用类型,和数字比较永远不会满足<18.5的条件,必须调用函数并传入参数拿到计算结果后再判断。
  • 原函数返回四舍五入后的整数,虽然这个案例里结果确实小于18.5,但如果需要更精确的BMI判断,可能需要保留原始计算值(比如18.49这类接近临界值的情况)。

修复后的代码(保留原函数四舍五入逻辑)

function bmiCalculator (weight, height) {
   var ecuation= (weight / Math.pow(height, 2));
 return Math.round(ecuation);
}

// 先调用函数获取BMI结果,再进行条件判断
const bmiValue = bmiCalculator(20, 2.20);
if(bmiValue < 18.5){
 console.log("you are so underweight")
}

console.log(bmiValue)

更精确的版本(保留原始BMI值用于判断)

如果需要基于精确BMI值做判断,只在输出时四舍五入,可以这样写:

function bmiCalculator (weight, height) {
   // 返回精确计算值,不做四舍五入
   return weight / Math.pow(height, 2);
}

const bmiValue = bmiCalculator(20, 2.20);
if(bmiValue < 18.5){
 console.log("you are so underweight")
}

// 输出时再处理成整数
console.log(Math.round(bmiValue))

修复后效果

运行代码后会先输出you are so underweight,再输出BMI值4,完全符合预期逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:55:20