如何找到每一行的最低值并将其排除在外,以便从数组中找到新的平均值



我在获取与给定输出匹配的输出时遇到问题。我制作了结构,但发现与我的输出几乎没有差异。

public void printStudentsAvgWithoutLowest() {
//do not declare variable here
double average = 0;
for (int i = 0; i < arrScores.length; i++) {
double lowest = 100;      //CHANGE HERE 
for (int j = 0; j < arrScores[i].length; j++) {
if (arrScores[i].length < lowest) {
lowest = arrScores[i][j];
}
}
for (int k = 0; k < arrScores[i].length; k++) {
if (arrScores[i][k] != lowest) {
average = average + arrScores[i][k];
}
}
average = average / (arrScores[i].length - 1);
System.out.printf("Student#%s Average (without lowest score): %.2fn", i, average);
average = 0;
}
System.out.printf("n");
}

这是我使用给定的txt文件制作的数组。

100.00     90.00    100.00     80.00     70.00
50.00     60.00     70.00     80.00    100.00
60.00     70.00    100.00     80.00     90.00
69.50     70.50     80.50     30.50      0.00
78.30     69.50     48.00     90.00    100.00
88.50     95.00    100.00     99.00      0.00

我需要找到每一行的平均值,其中不包括最低值。

我的输出如下:

Student#0 Average (without lowest score): 92.50
Student#1 Average (without lowest score): 65.00
Student#2 Average (without lowest score): 77.50
Student#3 Average (without lowest score): 62.75
Student#4 Average (without lowest score): 96.45
Student#5 Average (without lowest score): 95.63

给定的样本输出:

Student#0 Average (without lowest score): 92.50
Student#1 Average (without lowest score): 77.50
Student#2 Average (without lowest score): 85.00
Student#3 Average (without lowest score): 62.75
Student#4 Average (without lowest score): 84.45
Student#5 Average (without lowest score): 95.63

学生#1、2和4的输出与样本输出不同。

每一行都可以有不同的最低值,因此您应该在循环中定义变量。(此外,虽然它不会出现在您当前的输入中,但您可能需要考虑最低值多次出现的情况。要解决这个问题,您可以在找到最小值的同时对所有数组值求和,然后在除法之前从计算的和中减去该最小值。(

double lowest = Double.MAX_VALUE;
for (int j = 0; j < arrScores[i].length; j++) {
lowest = Math.min(lowest, arrScores[i][j]);
}

最新更新