首先,你可以在你的定义var i = 0
for循环, i <= N - 1
与i < N
相同。编写循环的更简单的方法是...... for(var i = 0; i < N; i++)
(也从上面删除var N = 0;
)。
现在没有必要将用户的数字放到数组中以获得它们的平均值。所有你需要的平均值是数字和数字的总和。
JavaScript的另一个很酷的事情是,它可以自由地将您正在使用的变量转换为适合所使用上下文的变量类型。这意味着N = parseInt(N);
在您的情况下不是必需的,因为它只能被视为循环中的整数。
如果考虑到上述两个注意事项,可以使用以下代码之一。
解决方案1:无阵列,只是保持数字之和量
//Prompt the user how many numbers they would like to enter
var N = prompt("How many numbers would you like to enter? ");
//Set sum to 0, which gives us a base to add each number to it.
var sum = 0;
//Complete this loop the same amount of times as the user entered in the prompt
for (var i = 0; i < N; i++) {
//Add the users response to the sum of responses
sum += parseInt(prompt("Enter your numbers: "));
}
//Write into the document the sum of
document.write("Avg. of entered numbers = " + sum/N);
但是,如果你真的想使用数组你的问题的状态,你可以使用下面的代码。
解决方案2:数组,同时保持和
//Prompt the user how many numbers they would like to enter
var N = prompt("How many numbers would you like to enter? ");
//Create an empty array to push elements to it
var nums = new Array();
//Set sum to 0, which gives us a base to add each number to it.
var sum = 0;
//Complete this loop the same amount of times as the user entered in the prompt
for (var i = 0; i < N; i++) {
//Get the users response to a variable
var response = parseInt(prompt("Enter your numbers: "));
//Add that variable to the sum
sum += response;
//And also push that variable to the array
nums.push(response);
}
//Write into the document the sum of the document
document.write("Avg. of entered numbers = " + sum/nums.length);
的跟踪如果您发现有我们用nums.length
代替N
。如果您遇到不确定用户输入多少个数字的情况,则可以使用数组长度来查看输入的数量。
现在,您可以在不使用for循环中的数组总和的情况下使用数组的同时执行更简单的方法。这利用了许多其他答案已经使用的reduce函数。
解决方案3:只是一个数组!
//Prompt the user how many numbers they would like to enter
var N = prompt("How many numbers would you like to enter? ");
//Create an empty array to push elements to it
var nums = new Array();
//Complete this loop the same amount of times as the user entered in the prompt
for (var i = 0; i < N; i++) {
//Push users response to the original array
nums.push(parseInt(prompt("Enter your numbers: ")));
}
//Use the reduce function to get the sum of the array, and then divide it by the amount of elements in the array.
document.write("Avg. of entered numddbers = " + (nums.reduce((a, b) => a + b)/nums.length));
'变种总和= 0;'环路,'总和+ =号码(NUMS [I])'循环内(后与提示线)和'VAR平均=总和/ N之前;循环之后。 – nnnnnn