【发布时间】:2016-03-30 02:12:33
【问题描述】:
我用纯代码编写了这个程序,但我对 Javascript 的了解还不够,无法正确掌握所有语法。我是一个初学者,请帮助我更正我的代码。它目前根本没有运行。我们仍在循环,这真的给我带来了麻烦。这是针对大学课程的。 (我知道格式不正确,这就是我寻求帮助的原因)
function main() {
alert("Welcome to the program");
var fatGrams = getFatGrams(fatGrams);
var calories = getCalories(fatGrams,calories);
var percentage = caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");
【问题讨论】:
-
从
function getFatGrams(fatGrams);和main中删除function关键字 -
displayPercentage有一个空的else块是否有原因...? -
不,没有理由。该循环是否应该以“end if”结束?
-
JS中没有
if.. then应该是if(){}else{} -
if (percentage < 0.3) { alert("The food is low in fat."); }这就是您所需要的。不需要else和end if,正如@me_digvijay 提到的,没有then。
标签: javascript loops if-statement