简体   繁体   English

以公制四舍五入 JavaScript BMI 计算器的结果编号

[英]Round a result number for JavaScript BMI calculator in metric

I am a bit stuck with my beginner project.我有点坚持我的初学者项目。 I am building a simple BMI calculator in metric and I do not understand where do I fail.我正在构建一个简单的 BMI 公制计算器,但我不明白我在哪里失败了。 I am using Math.round, but I am stuck at outputting result with rounded numbers as in the following code:我正在使用 Math.round,但我坚持使用四舍五入的数字输出结果,如下代码所示:

var heightInput = document.querySelector(".height-input-field");
var weightInput = document.querySelector(".weight-input-field");
var calculateButton = document.querySelector(".calculate");
var result = document.querySelector(".result");
var statement = document.querySelector(".result-statement");
var BMI, height, weight;

function calculationFunction() {
    height = heightInput.value;
    weight = weightInput.value;
    BMI = weight / Math.pow(height,2);
    result.innerText = Math.round(BMI*100)/100;

    if (BMI < 18.5) {
        statement.innerText = "Underweight";
        document.getElementById('result-color').style.backgroundColor="yellow";
    } else if ((BMI > 18.5) && (BMI < 24.9)) {
        statement.innerText = "Normal weight";
        document.getElementById('result-color').style.backgroundColor="green";
    } else if ((BMI > 25) && (BMI < 29.9)) {
        statement.innerText = "Overweight";
        document.getElementById('result-color').style.backgroundColor="yellow";
    } else {
        statement.innerText = "Obesity";
        document.getElementById('result-color').style.backgroundColor="red";
    }
}

calculateButton.addEventListener("click", calculationFunction);



/*
BMI Categories:
Underweight = <18.5
Normal weight = 18.5–24.9
Overweight = 25–29.9
Obesity = BMI of 30 or greater
*/

And I get 0 as a result: actual "app"结果我得到0:实际的“应用程序”

Would appreciate any help!将不胜感激任何帮助! Thanks!谢谢!

You are using a BMI metric formula that is meant for kg and meters , so your result is always a really small value and the Math.round line rounds it to 0.您正在使用适用于 kg 和的 BMI 度量公式,因此您的结果始终是一个非常小的值,并且Math.round线将其四舍五入为 0。

If you want to use cms (centimeters) then change your formula to如果您想使用 cms(厘米),请将您的公式更改为

BMI = weight (kg) / height (cm) / height (cm) * 10000 BMI=体重(kg)/身高(cm)/身高(cm)*10000

So in code, your BMI line changes to因此,在代码中,您的 BMI 行更改为

BMI = weight / height / height * 10000

I don't know about the formula you use to compute the BMI (and it does not count very much, it can be fixed easily anytime) but I can see a lot of things that can make the code easier to read, understand and reuse (or just make it cleaner).我不知道你用来计算 BMI 的公式(它不算很多,它可以随时轻松修复)但我可以看到很多可以使代码更易于阅读、理解和重用的东西(或者只是让它更清洁)。

Your code fail miserably and tell that the persons having BMI equal to 18.5 or between 24.9 and 25 are "obese" because of the way you check the value of variable BMI against the range intervals.您的代码惨遭失败,并告诉 BMI 等于18.5或介于24.925之间的人是“肥胖” ,因为您检查变量BMI值与范围间隔的方式。
If BMI is not < 18.5 (the first if statement) then it automatically is >= 18.5 (there isn't other way);如果BMI不是< 18.5 (第一个if语句),那么它会自动>= 18.5 (没有其他方法); there is no need to check it against > 18.5 .没有必要对照> 18.5检查它。 Also, if the second if condition does not match it means that BMI >= 24.9 and your third check ignores the values between (and including) 24.9 and 25.0 ( 24.95 , for example).此外,如果第二个if条件不匹配,则意味着BMI >= 24.9并且您的第三个检查忽略(包括) 24.925.0 (例如24.95 )之间的值。

When you have to check a value against some interval limits compare it only against one boundary of each interval:当您必须根据某些间隔限制检查值时,仅将其与每个间隔的一个边界进行比较:

if (BMI < 18.5) {
  ...
} else if (BMI < 24.9) {           // 18.5 <= BMI because we are on the `else` branch
  ...
} else if (BMI < 29.9) {           // 24.9 <= BMI because on the `else` of the second `if`
  ...
} else {                           // 29.9 <= BMI
  ...
}

The function calculateFunction() uses some global variables ( heightInput , weightInput , result , statement ) and that makes difficult to assert what values it uses to do its computation. function calculateFunction()使用一些全局变量( heightInputweightInputresultstatement ),这使得很难断言它使用什么值来进行计算。 Also, it changes the document and this is also not visible when you check the place where the function is used.此外,它会更改文档,当您检查使用 function 的位置时,这也是不可见的。

Also, the name of the function does not describe what it does.此外,function 的名称并没有描述它的作用。 The word "function" in a function name is useless, it does not tell anything; function 名称中的“功能”一词是无用的,它没有说明任何内容; try to avoid using it.尽量避免使用它。 A better name for the function is calculateBMI() . function 的更好名称是calculateBMI()

Let the function do only the computation of the BMI and return it.让 function 只做 BMI 的计算并返回。 You can move the code that interacts with the document (gets values from inputs, puts the BMI into another field) into a separate function:您可以将与文档交互的代码(从输入中获取值,将 BMI 放入另一个字段)到单独的 function 中:

// The function that computes the BMI
function calculateBMI(height, weight) {
  // implement the correct formula to compute the BMI
  return weight / Math.pow(height, 2);
}

// The function that computes the description and the color
function getBMIDescription(BMI) {
  // depending on the BMI value compute the text and the color
  if (BMI < 18.5) {
    return { description: 'Underweight', color: 'yellow' };
  } else if (BMI < 24.9) {
    return { description: 'Normal weight', color: 'green' };
  } else if (BMI < 29.9) {
    return { description: 'Overweight', color: 'yellow' };
  } else {
    return { description: 'Obesity', color: 'red' };
  }
}

// The function that interacts with the document
function computeBMIandDisplay(doc) {
  // `doc` is the page document but we pass it as argument to make the things more clear

  // gather the input data
  let height = doc.querySelector('.height-input-field').value;
  let weight = doc.querySelector('.weight-input-field').value;

  // compute the BMI and find the associated description and color
  let BMI = calculateBMI(height, weight);
  let { description, color } = getBMIDescription(BMI);

  // put the values on screen
  // display the BMI with two decimals
  doc.querySelector('.result').innerText = BMI.toFixed(2);

  // display the description and the associated color
  doc.querySelector('.result-statement').innerText = description;
  doc.getElementById('result-color').style.backgroundColor = color;
}


// Install the click handler on the button
document.querySelector('.calculate').addEventListener('click', () => computeBMIandDisplay(document));

On row 11 where you assign variable value something is wrong.在您分配变量值的第 11 行,出现问题。 height at power 2 will be much bigger compared with weight, so the result will be lower than 1/2, rounded will be 0.与重量相比,2 次方的高度会大得多,因此结果将低于 1/2,四舍五入为 0。

You have to correct your formula你必须更正你的公式

Alright, thanks a lot for advice.好的,非常感谢您的建议。 I did see my mistakes.我确实看到了我的错误。 I am answering to this as I have came to a better result as follows:我正在回答这个问题,因为我得到了如下更好的结果:

var heightInput = document.querySelector(".height-input-field");
var weightInput = document.querySelector(".weight-input-field");
var calculateButton = document.querySelector(".calculate");
var result = document.querySelector(".result");
var statement = document.querySelector(".result-statement");
var BMI, height, weight;

function calculationFunction() {
    height = heightInput.value;
    weight = weightInput.value;
    BMI = weight / height / height * 10000;
    result.innerText = Math.round(BMI*100)/100;

    if (BMI < 18.5) {
        statement.innerText = "Underweight";
        document.getElementById('result-color').style.backgroundColor="yellow";
        document.getElementById('result-color').style.color="black";
    } else if ((BMI > 18.5) && (BMI < 24.9)) {
        statement.innerText = "Normal weight";
        document.getElementById('result-color').style.backgroundColor="green";
        document.getElementById('result-color').style.color="white";
    } else if ((BMI > 25) && (BMI < 29.9)) {
        statement.innerText = "Overweight";
        document.getElementById('result-color').style.backgroundColor="yellow";
        document.getElementById('result-color').style.color="black";
    } else {
        statement.innerText = "Obesity";
        document.getElementById('result-color').style.backgroundColor="red";
        document.getElementById('result-color').style.color="white";
    }
}

calculateButton.addEventListener("click", calculationFunction);

And here is the actual https://theshadyslim.github.io/BMI-Calculator/这是实际的https://theshadyslim.github.io/BMI-Calculator/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM