简体   繁体   中英

where am i doing wrong? JS

I am newbie at the Javascript and i just trying to learning functions it's a little bit hard but i do my best:). I am doing a function to calculate bmi like this;

 let calculateWeight = parseFloat(prompt("Enter your weight", )) let calculateHeight = parseFloat(prompt("Enter your height?")) function calculateBmi(weight, height) { let bmi = weight / (height * height) if (bmi < 18.5) { console.log("You are underweight") } else if (bmi > 18.6) { console.log("You are normal weight") } else if (bmi > 25) { console.log("you are overweigh") } return bmi; } console.log(calculateBmi(calculateWeight, calculateHeight))

if i enter my values 72 weight and 1.80 kilos it says you are normal weight yeah it's correct but whenever i enter my values >25 it's says again you are normal weight where am i doing wrong?

but whenever i enter my values >25 it's says again you are normal weight

Because there's no value greater than 25 which doesn't satisfy this condition:

} else if (bmi > 18.6) {

It sounds like you just want the first and third conditions, and everything else is "normal":

if (bmi < 18.5) {
  console.log("You are underweight")
} else if (bmi > 25) {
  console.log("you are overweigh")
} else {
  console.log("You are normal weight")
}

Each step in the switch is evaluated in order, and the first one that's met will execute.

In this case, any value above 18.6 will hit your second case. To get it to pass by yo the third case, you need an upper limit on the value.

...
else if (bmi>18.6 && bmi <= 25){
...

There is just a small issue in your calculateBmi function.

See, whenever Bmi is coming greater than 25, the second condition in your else if ladder gets satisfied and "You are normal weight" gets printed in the console.

Fix condition as done below, and your issue will be fixed.

 let calculateWeight = parseFloat(prompt("Enter your weight")) let calculateHeight = parseFloat(prompt("Enter your height?")) function calculateBmi (weight, height){ let bmi = weight / (height * height) if(bmi < 18.5){ console.log("You are underweight") }else if (bmi>18.6 && bmi<=25){ console.log("You are normal weight") }else if (bmi>25){ console.log("you are overweigh") } return bmi; } console.log(calculateBmi(calculateWeight, calculateHeight))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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