You've succeeded in avoiding including multi-digit numbers from the sum and average. The problem isn't in that, it's here:
avg = sum/(i+1);
That's not how averages work. An average is the sum divided by how many values went into making that sum. (The number of numbers you added to sum
.)
Keep track of how many numbers you added to sum
, and use that count to calculate the average.
Side note: A couple of notes on the code, just for what they're worth:
- Your code is currently relying on implicit conversion from string (what the user types in) to number (what you use with
sum
). Although it works in this example, I strongly recommend doing the conversion explicitly. My other answer here (also on SO) lists your various options for doing that.
- You've used both
let
and var
in your code. I suggest never using var
, it has no place anymore in modern JavaScript. Use let
if you need to let the variable's value change (as with sum
), and const
when you don't.
- You're missing one
;
(after the assignment statement assigning to average
). (You can rely on Automatic Semicolon Insertion if you like [I don't recommend relying on it, but some others do], but whichever way you go, it's best to know the rules and then consistently do or don't include your ;
.)
- I suggest declaring your variables in the innermost scope you can declare them in. There's no reason for
i
to be global in your code, just make it local to the do-while
loop body.
- Obviously in a very simple exercise like this it's mostly fine, but I recommend not getting used to
prompt
and alert
, they're relics from the 1990s and behave in very unusual (and sometimes problematic) ways compared to most functions in JavaScript.