實際上,您提供的代碼要求在while()
循環的每個週期內輸入3個輸入。因此,如果您只需要3個號碼,那麼您將不需要0循環。
我已經用2個函數寫出了一組真正基本的代碼,它們在數組中找到最大值和最小值。
var totalSum = 0;
// initialize the array with 0s.
var inputNums = [0, 0, 0];
// Loop through the input number array and ask for a number each time.
for (var i = 0; i < inputNums.length; i++) {
inputNums[i] = parseInt(prompt("Enter Number #" + (i + 1)));
//Add the number to the total sum
totalSum = totalSum + inputNums[i];
}
// Calculate results
var average = totalSum/inputNums.length;
document.write("Total Inputs: " + inputNums.length + "<br>");
document.write("Sum: " + totalSum + "<br>");
document.write("Average: " + average + "<br>");
document.write("Max: " + findMaxValue(inputNums) + "<br>");
document.write("Min: " + findMinValue(inputNums) + "<br>");
function findMaxValue(numArray) {
// Initialize with first element in the array
var result = numArray[0];
for(var i = 1; i < numArray.length; i++) {
// loops through each element in the array and stores it if it is the largest
if(result < numArray[i]) {
result = numArray[i];
}
}
return result;
}
function findMinValue(numArray) {
// Initialize with first element in the array
var result = numArray[0];
for(var i = 1; i < numArray.length; i++) {
// loops through each element in the array and stores it if it is the smallest
if(result > numArray[i]) {
result = numArray[i];
}
}
return result;
}
不幸的是,SO中的片段系統不支持prompt()
。
我在這裏提出了一個的jsfiddle:https://jsfiddle.net/hrt7b0jb/
什麼是你,而這樣做面臨的問題?在循環之前創建一個數組,並將結果推送到每個結果中的數組。然後迭代後,計算所需的信息,然後顯示在屏幕上。 – niyasc