计算bmi并返回字符串的函数

时间:2019-05-25 05:03:08

标签: javascript

我正在上一门在线课程,但遇到实践问题。我要建立一个bmi(体重指数)计算器,该计算器返回一个值,让用户知道他们的bmi是什么。

我尝试使用if语句解决此问题,但验证程序抛出错误,指出我的解决方案不正确。有人可以看到我的代码有什么问题吗?

var interpretation = "";

function bmiCalculator (weight, height) {
    bmi = weight / Math.pow(height, 2);

    if (bmi < 18.5) {
        interpretation = "Your BMI is " + bmi + ", so you are underweight";
    } else if (bmi => 18.5 && bmi <= 24.9) {
        interpretation = "Your BMI is " + bmi +", so you have a normal weight";
    } else {
        interpretation = "Your BMI is " + bmi + ", so you are overweight";
    }

   return interpretation;
}

3 个答案:

答案 0 :(得分:1)

您需要使用模板字符串或字符串串联在最终输出中添加bmi

以下是使用模板字符串的方法示例:-

var interpretation = "";

function bmiCalculator(weight, height) {
    bmi = weight / Math.pow(height, 2);

    if (bmi < 18.5) {
        interpretation = `Your BMI is ${bmi}, so you are underweight`;
    } else if (bmi >= 18.5 && bmi <= 24.9) {
        interpretation = `Your BMI is ${bmi}, so you have a normal weight`;
    } else {
        interpretation = `Your BMI is ${bmi}, so you are overweight`;
    }

    return interpretation;
}

您的代码可以进一步改进

function bmiCalculator(weight, height) {
    let bmi = weight / Math.pow(height, 2);
    let interpretation = `Your BMI is ${bmi}, so you `
    if (bmi < 18.5) {
        interpretation += `are underweight`;
    } else if (bmi < 25) {
        interpretation += `have a normal weight`;
    } else {
        interpretation += `are overweight`;
    }

    return interpretation;
}

答案 1 :(得分:0)

总结上面的评论,这是一个简化的解决方案,将做同样的事情:

function calc(weight, height) { 
  var bmi = weight/(height*height);
  var bmis=bmi.toFixed(2);
  return `Your BMI is ${bmis}, so you `+
       (bmi<18.5?'are underweight'
      : bmi<25  ?'have a normal weight'
      :          'are overweight'); }

我将.toFixed(2)舍入到两位数字,因为没有人会对13位精度的答案感兴趣。

尽管Math.pow(height,2)在数学上是正确的,但是直接乘积height*height的计算量却大大减少。

(在此示例中无关紧要,但是在您运行多个迭代或在大型数组上工作的情况下,这可能很重要。)

答案 2 :(得分:-1)

所以我终于能够使它与此一起工作:

function bmiCalculator (weight, height) {
    var bmi = weight/(height*height);
    if (bmi > 24.9){
        return "Your BMI is " + bmi + ", so you are overweight.";
    }
    if (bmi >= 18.5 && bmi <=24.9){
        return "Your BMI is " + bmi + ", so you have a normal weight.";
    }
    if (bmi < 18.5){
        return "Your BMI is " + bmi + ", so you are underweight.";
    }
}

在这种情况下,找出if语句的顺序很重要!