简体   繁体   English

在While循环中嵌套if / else

[英]Nested if/else in While loop

I'm trying to make a program that determines if a grade entered is passing or failing. 我正在尝试创建一个程序来确定输入的成绩是否正在通过或失败。 It stops when the user enters -1. 当用户输入-1时它停止。 Once the user does enter -1, it has to print out the average of the passing scores and the total amount of scores. 一旦用户输入-1,就必须打印出通过分数的平均值和总分数。 It's not really working correctly though. 但它并没有真正起作用。 What am I doing wrong? 我究竟做错了什么?

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.

Try working through it by hand. 尝试手工完成它。 The user enters the very first grade. 用户进入一年级。 Then the loop starts. 然后循环开始。 Immediately, you ask for a new grade, discarding the first one. 马上,你要求新的成绩,丢弃第一个成绩。 If you move the prompt down to the end of the loop, it should work. 如果将提示移动到循环的末尾,它应该可以工作。 Like this: 像这样:

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++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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