首先,你可以在你的定義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