まず、あなたがあなたのためのループでvar i = 0
を定義することができますを確認し、 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:配列、あなたはそこに気づいた場合、我々はnums.length
代わりのN
を使用
//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);
和のトラックを維持しながら。ユーザーが入力する数字の数が不明な場合は、配列の長さを使用して入力された数を確認できます。
ここでは、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));
'VAR合計= 0;'ループ、 '和+ =番号(NUMS [I])'ループ内、および 'VARの平均= SUM(プロンプトの行後)/ Nの前に; 'ループの後。 – nnnnnn