为什么我的函数没有返回准确的计数

Why is my function not returning accurate count?

本文关键字:返回 我的 函数 为什么      更新时间:2023-09-26

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

您的函数没有返回正确的值,因为您正确地分配了countcount2。如果在末尾运行代码,则countcount2将等于nums.length。这是因为您正在for循环中使用它们。在循环中,你也引用了i,(我相信)在这一点上也等于nums.length

我想你想要这样的东西:

count = 0;
count2 = 0;
for(i = 0; i < nums.length; i++) 
{
    if(nums[i] > avg)
    {
        count++; //Increase the count of numbers above the average
    }
    else if(nums[i] < avg)
    {
        count2++;  //Increase the count of numbers below the average
    }
}   

您可能想阅读scope和for循环,因为您对它们似乎有点困惑。

编辑

如果你想要数组中最大和最小的值,你可以这样做:

//Assign the values to the first element by default
var biggest = nums[0];
var smallest = nums[0];
for(var i = 1; i < nums.length; i++)
{
    //Set biggest to the larger number, either biggest or the current number
    biggest = Math.max(biggest, nums[i]);
    //Set smallest to the smaller number, either biggest or the current number
    smallest = Math.min(smallest, nums[i]);
}

注意:这假设您在数组中至少有1个值