我正在上一门在线课程,在这门课上我遇到了一道练习题。我要建立一个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;
}发布于 2019-05-25 13:09:40
您需要使用模板字符串或字符串连接在最终输出中添加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;
}发布于 2019-05-25 13:36:30
总结上面的评论,这里是一个简化的解决方案,它将做同样的事情:
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的计算要容易得多。
(在本例中这并不重要,但在运行多次迭代或处理大型数组的情况下,这一点可能很重要。)
发布于 2019-05-25 13:53:08
所以我终于能够让它用这个来工作:
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语句的顺序非常重要!
https://stackoverflow.com/questions/56301864
复制相似问题