0

I'm trying to make a program that determines if a grade entered is passing or failing. It stops when the user enters -1. Once the user does enter -1, it has to print out the average of the passing scores and the total amount of scores. 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.
Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141
user1765804
  • 151
  • 2
  • 3
  • 9

1 Answers1

2

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++;
}
Tayacan
  • 1,836
  • 10
  • 15
  • oh ok, that makes sense. For the life of me, I could not figure out why it would do that. It actually seemed to be discarding the second value entered, but this works. Thanks. – user1765804 Nov 14 '12 at 15:10
  • Hmm. I tested it, and it discarded the first one. For some reason, the average was wrong too before I changed it, but it seems to work now. – Tayacan Nov 14 '12 at 15:16