我被指示创建一个程序,从用户那里获取 10 个号码。然后它应该显示它并找出它与平均值(输入的 10 个数字)的差异。我已经弄乱了代码一段时间,但我不确定我做错了什么。当我在浏览器中打开时,计算不正确。
var number = new Array(10);
for(var i=0; i<10; i++) {
var number = prompt("PLEASE ENTER A NUMBER");
total = parseInt(number);
average = total/10;
document.write("The difference from the average for the number, " + number +
"is equal to " + (number - average) + "<br>");
}
最佳答案
一开始你根本不需要数组,你只需要总和:
var total = 0;
for (var count = 1; count <= 10; count++) {
const number = parseInt(prompt("A number (again):"));
//increase total by the inputted number
total += number;
const average = total / count;
document.body.innerHTML += `The ${count} number is ${number}, the average is ${average} and they differ by ${average - number}`;
}
您可能会注意到,我尽可能多地使用了 const
(因为常量的东西更容易处理),以及模板文字( >${..}
stuff ) 在我看来这使它更具可读性。
关于javascript - 如何将提示中的多个输入添加到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47338870/