简体   繁体   English

我想在给定数组中找到平均值,并在 java 中找到最接近该平均值的数字

[英]I want to find the average in a given array, and find the closest number to that average in java

I want to calculate the number closest to the average of the array, I have finished calculating the average but I have no idea how to find the closest number to that average.我想计算最接近数组平均值的数字,我已经完成了平均值的计算,但我不知道如何找到最接近该平均值的数字。

public class ClosestToTheArray {
int array [] = new int[]{1, 2, 3 ,4 ,5, 6 ,7 ,8};
int sum;
int sum2;

public void findAverage(){
    double avg;
    double lol = 0;
    double smthelse;
    for(int i =0; i < array.length; i++){
        sum += array[i];
    }
    avg = sum/array.length;
}

public static void main(String [] args){
    ClosestToTheArray test = new ClosestToTheArray();
    test.findAverage();
}

} }

To find the average in the given array and find the number which is closest to the average,要在给定数组中找到平均值并找到最接近平均值的数字,

public static void main(String[] args)
{
    int array[] = new int[]
    { 1, 2, 3, 4, 5, 6, 7, 8 };
    int sum=0;

    double avg;
    for (int i = 0; i < array.length; i++)
    {
        sum += array[i];
    }
    avg = sum / array.length;
    System.out.println(avg);
    
    double difference = Math.abs(array[1] - avg);
    Integer closest = array[1];
    for (int i = 0; i < array.length; i++)
    {
        double diff = Math.abs(array[i] - avg);
        if(difference > diff)
        {
            difference = diff;
            closest = array[i];
        }
    }
    System.out.println(closest);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM