0

My syntax was just fixed for my code and it is now running. I am having problems adding two numbers instead of my program concatenating the values. Thanks for your help, Ben

var averagetotal = (grades[j]+averagetotal);

Here is the whole code.

var numberofgrades = prompt("How many grades do you want to calculate?");
var countingvalue = 0;
var grades = [];
var tempgrade = 0;
var averagetotal = 0;
for(var i=0;i<=numberofgrades;i++){
if(countingvalue!=numberofgrades){
    if(countingvalue==1){
    var tempgrade= prompt("What is your "+(countingvalue+1)+"st grade?");
    grades.push(tempgrade);
    countingvalue++;
}
    else if(countingvalue!=1){
    var tempgrade= prompt("What is your "+(countingvalue+1)+"th grade?");
    grades.push(tempgrade);
    countingvalue++;
    }
}
else if(countingvalue==numberofgrades)
{
    for(var j=0;j<numberofgrades;j++){
        var averagetotal = (grades[j]+averagetotal); // problem line
        alert(j+" "+averagetotal); //checking values
    }
}


}
alert(grades[0]); //just checking values
alert(grades[1]); //checking values
alert(averagetotal);
alert("Your average grade is: "+(averagetotal/numberofgrades));

2 Answers2

0

You can add numbers that are represented as strings in a couple of ways in javascript.

To ensure that you're dealing with numbers, use Number() as in this example

var x = '1';
var y = '2';

x + y === '12'; // true
Number(x) + Number(y) === 3; // true
manonthemat
  • 6,101
  • 1
  • 24
  • 49
0

change

var tempgrade = prompt("What is your "+(countingvalue+1)+"th grade?");

to:

var tempgrade = parseInt(prompt("What is your "+(countingvalue+1)+"th grade?"));

The parseInt function will make sure (as long as the input is a number) that

grades.push(tempgrade);

will be adding tempgrade to the array as a number and not as a String.

This means that

grades[j] + averagetotal

will be adding two numbers together now.

Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29