0

I'm trying to write a little snippet where prompts ask the user for 5 numbers and computes the total of the numbers.

So far I have this:

var counter, number, total;

for(counter = 0; counter < 5; counter++) {
  number = parseFloat(prompt("Enter a number:"));
  total += number;
}

document.write("The total is " + total + ".");

However the 'total' returns " " for example, rather than a sum of 15.

How do I fix this?

Thanks in advance!

6
  • *where it prompts Commented Jul 2, 2017 at 11:46
  • 1
    Add this total = 0. Commented Jul 2, 2017 at 11:48
  • Initialize total to zero. Commented Jul 2, 2017 at 11:48
  • Worked, thank you! Commented Jul 2, 2017 at 11:52
  • However the 'total' returns "12345" for example - This is probably when you say total = "" and not the current code in the question. The code in the question prints The total is NaN. Commented Jul 2, 2017 at 11:59

2 Answers 2

3

You should initialize your total var to 0:

var counter, number, total = 0;

for(counter = 0; counter < 5; counter++) {
  number = parseFloat(prompt("Enter a number:"));
  total += number;
}

document.write("The total is " + total + ".");

Sign up to request clarification or add additional context in comments.

2 Comments

number is useless: You could write: total += parseFloat(prompt("Enter a number:"));
agree @F.Hauri but I only copied his code and fixed his main problem. code optimization should be his thing
2

You have to set total to 0, like this:

var counter, number, total = 0;

for(counter = 0; counter < 5; counter++) {
  number = parseFloat(prompt("Enter a number:"));
  total += number;
}

document.write("The total is " + total + ".");

1 Comment

What mean "& co"? First line dont set any other variable than total to 0! 3 variables are declared, but only one is initialised.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.