What I need to achieve are the following conditions:
here's what I have, and I understand that I'm missing some key logic in here, any suggestions?
while (true) {
var userInput = prompt("Enter a number between 1 and 100:");
var num = parseInt(userInput, 10);
if (num >= 1 && num <= 100) {
var nums = 0;
nums += num;
var counter = 0;
counter++;
} else if (userInpuft === null) {
alert(nums / counter);
alert(counter);
break;
}
}
The mean of a set of numbers can be calculated incrementally, without having to save all the numbers anywhere. All you need is the previous mean and the count of numbers that have been entered.
Consider the formula mean = total/count
. If you know mean
and count
, you can invert the equation to total = mean * count
.
When you get a new number, the count goes up by 1, and the new number is added to the total. So the formula is mean = (mean * (count - 1) + new_number)/count
.
let count = 0;
let mean = 0;
while (true) {
let input = prompt("Enter a number");
if (input === null) {
break;
}
new_number = parseFloat(input);
if (!isNaN(new_number) && new_number >= 1 && new_number <= 100) {
count++;
mean = (mean * (count - 1) + new_number) / count;
alert(`Count = ${count}, Mean = ${mean}`);
}
}