扩展代码我一直在为补充跟踪器工作,但是我的当前函数没有返回大于平均“均值”的数字的精确计数,也没有返回低于均值平均值的整数计数。我也在代码中注释了两个问题,因为我不太明白为什么将数组设置为索引[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