0

I did an exercise today in college, and it was a JavaScript program to calculate the average score of pupils in a test.

Here is my code:

<!DOCtype html>

<html>
<head>
<title>While loop</title>
</head>
<body>
<script>

    //The total score of all pupils
    var total = 0;
    //The number of scores
    var count = 1;

    while (count <= 10) {
        grade = prompt("Insert the grade:");
        total = total + grade;
        count++;
        }

    var average = +total / 10;
    document.write("The average is " + average);

</script>

</body>
</html>

The values I put in are 10-100 going up in 10s. So I put in these 10 values "10, 20, 30, 40, 50, 60, 70, 80, 90, 100" And instead of getting the average, I'm getting all of these values side by side.

What am I doing wrong?

Liam
  • 27,717
  • 28
  • 128
  • 190
  • 3
    Possible duplicate of [How do I convert a string into an integer in JavaScript?](http://stackoverflow.com/questions/1133770/how-do-i-convert-a-string-into-an-integer-in-javascript) – Liam Nov 01 '16 at 11:52
  • 1
    Tl;Dr Javascript is not strongly typed and it will corerce variables into whatever type it deems fit depending on how you use them. `+` is concat for a string but add for an integer. – Liam Nov 01 '16 at 11:54

2 Answers2

5

grade = prompt("Insert the grade:"); is the problem. The prompt is taking your input as a string, and in JS, adding two strings just concatenates the values. So parse your inputs:

grade = +prompt("Insert the grade:"); //+ is shorthand for casting to a number

Or use parseInt

grade = prompt("Insert the grade:");
var numberGrade = parseInt(grade);

FYI - all the numbers you're adding have to be integers - else it'll just end up as a string again, example:

10 + 10; //20
10 + "10" //1010
10 + 10 + "10" //2010
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Thank you, this answer is much easier to understand than the answer of what this question was a duplicate of. :) – Denisowator Nov 01 '16 at 11:58
1

Change total = total + grade; to total = total + parseInt(grade);

when you write total = total + grade js concatenate total and grade as strings

Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46