var bmr=100;
var sum=50;
var caloriesneeded = 0;
var activitylevel = prompt("Enter your activity level ");
document.write( "<p>You need to consume ");
if ( activitylevel == "0"){
document.write (caloriesneeded = bmr * 1.2 );
}
else if (activitylevel == "1-3"){
document.write(caloriesneeded = bmr * 1.375 );
}
else if (activitylevel == "3-5"){
document.write(caloriesneeded = bmr * 1.55 );
}
else if (activitylevel == "6-7"){
document.write (caloriesneeded = bmr * 1.725 );
}
else if (activitylevel == "2x"){
document.write(caloriesneeded = bmr * 1.9 );
}
else {
document.write("invalid");
}
if (caloriesneeded > sum){
document.write ("<p>You still can consume " + (caloriesneeded - sum) +
"kcal of food</p>");
}
else if (caloriesneeded == sum){
document.write("<p>You have consumed just enough " + (caloriesneeded -
sum) + "kcal of food</p>");
}
else if (caloriesneeded < sum){
document.write ("<p>You have over consumed " + (sum - caloriesneeded )
+ "kcal of food</p>");
}
仅代码的前半部分有效,并且所需卡路里>总和,所需卡路里==总和和所需卡路里
最佳答案
var bmr=100;
var sum=50;
var caloriesneeded = 0;
var activityLevels = {
"0": 1.2,
"1-3": 1.375,
"3-5": 1.55,
"6-7": 1.725,
"2x": 1.9
};
var output = "";
function calculateCaloriesNeeded(activityLevel) {
if ( typeof activityLevels[activityLevel] !== "undefined") {
caloriesneeded = bmr * activityLevels[activityLevel];
return true;
}
return false;
}
var currentActivityLevel = prompt("Enter your activity level ");
if (calculateCaloriesNeeded( currentActivityLevel )) {
// input has been valid
output += "<p>You need to consume " + caloriesneeded + "</p>";
if (caloriesneeded > sum){
output += "<p>You still can consume " + (caloriesneeded - sum) + "kcal of food</p>";
} else if (caloriesneeded == sum){
output += "<p>You have consumed just enough " + (caloriesneeded - sum) + "kcal of food</p>";
} else if (caloriesneeded < sum){
output += "<p>You have over consumed " + (sum - caloriesneeded ) + "kcal of food</p>";
}
} else {
output += "<p>Your input is not valid. Please choose one of “0”, “1-3”, “3-5”, “6-7” or “2x”.</p>";
}
document.write( output );
清洁一点的方法。