擴展代碼我一直在爲補充跟蹤器工作,但是我的當前函數沒有返回大於平均「均值」的數字的精確計數,也沒有返回低於均值平均值的整數計數。我也在代碼中註釋了兩個問題,因爲我不太明白爲什麼將數組設置爲索引[0]。我從評論中學到了很多東西,並在這裏尋找答案。非常感謝這個網站的存在!希望對這個問題有更多的希望。爲什麼我的函數沒有返回精確的計數?
function suppArray() {
var nums = new Array(); //create array
var sum = 0; //variable to hold sum of integers in array
var avg = 0; //variable to hold the average
var i;
var count = 0;
var count2 = 0;
var contents = ''; //variable to hold contents for output
var dataPrompt = prompt("How many numbers do you want to enter?", "");
dataPrompt = parseInt(dataPrompt);
for(i = 0; i <= dataPrompt - 1; i++) { //loop to fill the array with numbers
nums[i] = prompt("Enter a number","");
nums[i] = parseInt(nums[i]);
contents += nums[i] + " "; //variable that will be called to display contents
sum = sum + nums[i];
}
avg = sum/nums.length;
for(i = 0; i < nums.length; i++) { //loop to find the largest number
var biggest = nums[0]; //why does this have to be index 0 and not 'i' ?
if(nums[i] > biggest)
biggest = nums[i]; //largest integer in array
}
for(i = 0; i < nums.length; i++) { //loop to find smallest integer
var smallest = nums[0]; //why does this have to be the index 0 and not 'i' ??
if(nums[i] < smallest)
smallest = nums[i]; //smallest integer in array
}
for(count = 0; count < nums.length; count++) { //count of numbers higher than average
if(nums[i] > avg)
count = nums[i];
}
for(count2 = 0; count2 < nums.length; count2++) { //count of numbers lower than average
if(nums[i] < avg)
count2 = nums[i];
}
}
不確定,但對於(i = 0; i <= dataPrompt - 1; i ++)應該沒有-1並將<=改爲< – 2015-04-01 14:39:10
看起來您對'var smallest'有一些範圍問題,它已設置每次運行for循環。我不確定你在 – 2015-04-01 14:39:53
最小和最大值應該設置爲nums [0],但在for循環之前。 – jcubic 2015-04-01 14:39:55