gpt4 book ai didi

java - 查找数组的修剪平均值(不包括最小值和最大值)

转载 作者:行者123 更新时间:2023-12-02 08:47:25 24 4
gpt4 key购买 nike

正在寻找数组的修剪平均值,但对如何使用方法实现它感到困惑。请提出有关如何实现并使用某种方法获得实际修剪平均值的任何想法。这就是我目前所拥有的一切。 TIA!

public static void main(String[] args) {
// Program 1: Average, Min, Max, Trimmed Average of Array
Scanner in = new Scanner(System.in);
int array[] = new int[] {88,48,96,85,97,68,97};

// Calling getMax() method for getting max value
int max = getMax(array);
System.out.println("Maximum: " + max);

// Calling getMin() method for getting min value
int min = getMin(array);
System.out.println("Minimum: " + min);

// calling getAvg() method for getting avg value
double avg = getAvg(array);
System.out.println("Average: " + avg);

// calling getMean() method for getting trimmed mean value
double mean = getTrim(array);
System.out.println("Trimmed mean: " + mean);
}

// Method for getting the maximum value
public static int getMax(int[] inputArray) {
int maxValue = inputArray[0];
for (int i = 1; i < inputArray.length; i++) {
if (inputArray[i] > maxValue) {
maxValue = inputArray[i];
}
}
return maxValue;
}

// Method for getting the minimum value
public static int getMin(int[] inputArray) {
int minValue = inputArray[0];
for (int i = 1; i < inputArray.length; i++) {
if (inputArray[i] < minValue) {
minValue = inputArray[i];
}
}
return minValue;
}

//Method for getting the avg value
public static double getAvg(int[] inputArray) {
double total = 0;
double avg;
for(int i=0; i<inputArray.length; i++){
total = total + inputArray[i];
}
return avg = total / inputArray.length;
}

//Method for getting the trimmed mean value
public static double getTrim(int[] inputArray) {

}

}

最佳答案

试试这个:

public static double avgExcludingMinMax(int[] inputArray) {
int max = inputArray[0];
int min = inputArray[0];
long sum = 0;
for(int i = 0; i < inputArray.length; i++){
sum = sum + inputArray[i];
if (inputArray[i] > max) {
max = inputArray[i];
}
if (inputArray[i] < min) {
min = inputArray[i];
}
}
return ((double) (sum - max - min)) / (inputArray.length - 2);
}

请注意,如果 inputArray.length == 0,这将引发异常;

如果您想了解有关此类操作的统计背景的更多信息,请查看 https://en.wikipedia.org/wiki/Trimmed_estimatorhttps://en.wikipedia.org/wiki/Winsorizing !

关于java - 查找数组的修剪平均值(不包括最小值和最大值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60986768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com