user3602768
user3602768

Reputation: 9

Input scores and count the average

I am so new to JavaScript even though I know that it should be pretty easy, so please help! I know that there were some similar topics but I need to use this template

here is my assignment:

Allow the user to input seven different scores Compute the average of all those scores Display the average on the screen

enter image description here

What I have so far:

// init vars, get input from user
var scores = [1,2,3,4,5,6,7];

score[0] = (prompt("Type in a Score 1 of 7") )
score[1] = (prompt("Type in a Score 2 of 7") )
score[2] = (prompt("Type in a Score 3 of 7") )
score[3] = (prompt("Type in a Score 4 of 7") )
score[4] = (prompt("Type in a Score 5 of 7") )
score[5] = (prompt("Type in a Score 6 of 7") )
score[6] = (prompt("Type in a Score 7 of 7") )

function calculate() {
    for (var i = 0; i < scores.length; i++) {
        total += score[i];
    }
    average = (total / scores.length).toFixed(2);
}

function getscores() {
    while (scores.length < 7) {
        scores.push(parseInt(prompt("Please input a score")));
    }
}

getScores();
calculate();
showScores();

function showScores() {
    document.write("The average of those scores is: " + average);
}

Upvotes: 0

Views: 4787

Answers (2)

Sumner Evans
Sumner Evans

Reputation: 9155

This should work:

var score = [];

function getScores() {
    while (score.length < 7) {
        score.push(parseInt(prompt("Please input a score")));
    }
}

function calculate() {
    var total = 0;
    for (var i = 0; i < score.length; i++) {
        total += score[i];
    }
    average = (total / score.length).toFixed(2);
}

function showScores() {
    alert("The average of those scores is: " + average);
}

getScores();
calculate();
showScores();

Working JSFiddle Example

Upvotes: 0

potashin
potashin

Reputation: 44601

You should define total with var and assign in to 0:

 function calculate() {
   var total = 0;
   for (var i = 0; i < scores.length; i++) {
     total += scores[i];
   }
    average = (total / scores.length).toFixed(2);
 }

Also you should set average global just like you did with scopes:

var average;

Upvotes: 2

Related Questions