我被指示创建一个从用户那里获取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>");
}
答案 0 :(得分:2)
起初你根本不需要阵列,你只需要总结一下:
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}`;
}
&#13;
您可能会注意到我已尽可能多地使用const
(导致常量事情更好处理),以及模板文字({{1在我看来,这使得它更具可读性。
答案 1 :(得分:0)
var number = new Array(10);
var total; //create a variable for your total
var average; //create a variable for your average
for(var i=0; i<10; i++)
{
var number[i] = prompt("PLEASE ENTER A NUMBER"); //make sure all the
//numbers have their
//own ids which is 'i'
//in this case
total += parseInt(number); //this basically means total = previoustotal
//+ newly parsed number
}
average = total/10; //leave this outside because you want to do the
//calculations at the end
for(var i=0; i < number.length ; i++)
{
document.write("The difference from the average for the number," +
number[i] + "is equal to " + (number[i] - average) + "<br>");
} //this will print out a difference output for all 10 numbers you
//inputted
不确定您的CSS和HTML是如何制作的,所以我只是将br留在那里
答案 2 :(得分:0)
这是因为您的每个输入都会在您获得其他数字之前开始计算平均值。您可能希望等待所有输入,然后进行计算。
总而言之,你必须添加数字。可能你需要的只是让你的数学正确。
var number = new Array(10);
var total = 0;
for(var i=0; i<10; i++) {
number[i] = parseInt(prompt("PLEASE ENTER A NUMBER\n"));
total += parseInt(number[i]);
}
var average = total / number.length
for(var i=0; i<10; i++) {
alert("The difference from the average for the number, " + number[i] +
"is equal to " + (number[i] - average));
}
答案 3 :(得分:0)
您好,亲爱的朋友,首先我有一个问题,您是否为控制台或网络编码?
如果您为控制台做,您必须这样写:
var number = new Array(10);
var total = 0;
for(var i=0; i<10; i++) {
var number = console.log("PLEASE ENTER A NUMBER\n");
total = total + parseInt(readline());
}
average = total/10;
console.log("The difference from the average for the number, " + number +
"is equal to " + (number - average));
并且按照您的方式,您只需将代码更改为:
var number = new Array(10);
var total = 0 ;
for(var i=0; i<5; i++) {
var number = prompt("PLEASE ENTER A NUMBER");
total = total + parseInt(number);
}
average = total/5;
document.write("The difference from the average for the number, " + number +
"is equal to " + (number - average) + "<br>");
var number = new Array(10);
var total = 0 ;
for(var i=0; i<5; i++) {
var number = prompt("PLEASE ENTER A NUMBER");
total = total + parseInt(number);
}
average = total/5;
document.write("The difference from the average for the number, " + number +
"is equal to " + (number - average) + "<br>");