Javascript 在While循环中嵌套if/else
我正在尝试制作一个程序来确定输入的分数是及格还是不及格。当用户输入-1时,它停止。一旦用户输入-1,它就必须打印通过分数的平均值和总分数。不过,它并没有真正正常工作。我做错了什么Javascript 在While循环中嵌套if/else,javascript,loops,Javascript,Loops,我正在尝试制作一个程序来确定输入的分数是及格还是不及格。当用户输入-1时,它停止。一旦用户输入-1,它就必须打印通过分数的平均值和总分数。不过,它并没有真正正常工作。我做错了什么 var countTotal=0; //variable to store total grades. var countPassing=0; //variable to store total passing scores. var x= 0; //variable to contain sum of
var countTotal=0; //variable to store total grades.
var countPassing=0; //variable to store total passing scores.
var x= 0; //variable to contain sum of all passing scores.
var grade=parseInt(prompt("Please enter a grade."));
while (grade != (-1*1))
{
if (grade > 65) {
grade=parseInt(prompt("Please enter a grade."));
document.write(grade + " is passing.<br>");
x=x+grade;
countPassing++;
}
else {
grade=parseInt(prompt("Please enter a grade."));
document.write(grade + " is failing.<br>");
}
countTotal++;
}
//Loop ends
document.write("Total # of grades: " + countTotal); //Prints out total # of passing scores.
document.write("Passing average: " + ((x)/(countPassing))); //Prints out average of all passing scores.
var countTotal=0//变量来存储总等级。
var countPassing=0//变量来存储总通过分数。
var x=0//变量,以包含所有及格分数的总和。
var grade=parseInt(提示(“请输入等级”);
而(等级!=(-1*1))
{
如果(等级>65){
grade=parseInt(提示(“请输入等级”);
文件。书写(成绩+“通过。
”;
x=x+等级;
countPassing++;
}
否则{
grade=parseInt(提示(“请输入等级”);
文件。写入(分数+“不合格。
”;
}
countTotal++;
}
//环端
文件。填写(“总成绩:+countTotal”)//打印出通过考试的总分数。
文件。写入(“通过平均值:+((x)/(计数通过))//打印出所有及格分数的平均值。
试着用手操作。用户进入一年级。然后循环开始。立即,你要求一个新的等级,放弃第一个等级。如果将提示向下移动到循环的末尾,它应该可以工作。像这样:
while (grade != (-1*1))
{
if (grade > 65) {
document.write(grade + " is passing.<br>");
x=x+grade;
countPassing++;
}
else {
document.write(grade + " is failing.<br>");
}
grade=parseInt(prompt("Please enter a grade."));
countTotal++;
}
while(等级!=(-1*1))
{
如果(等级>65){
文件。书写(成绩+“通过。
”;
x=x+等级;
countPassing++;
}
否则{
文件。写入(分数+“不合格。
”;
}
grade=parseInt(提示(“请输入等级”);
countTotal++;
}
为了满足我的好奇心。。。(grade!=(-1*1))
的要点是什么?(grade!=-1)
就足够了吗?是的,你完全正确,但我只是想确保它是一个整数。我对这个哈哈文档很陌生。write
是一个很好的工具。@user1765804:没关系,我只是想指出它。需要注意的是,parseInt应该为您解决这个问题。将radix
参数传递到parseInt
:parseInt(grade,10)
。否则,如果你得到一个以0开头的东西,它将被解释为八进制。就我的一生而言,我不明白它为什么会这样做。它实际上似乎在丢弃输入的第二个值,但这是可行的。谢谢,嗯。我测试了它,它丢弃了第一个。由于某种原因,在我改变平均值之前,它也是错误的,但现在它似乎起作用了。