如何显示最高和最低平均成绩? 我尝试了其他解决方案,但它无法正常工作
您能帮忙了解如何显示最高平均成绩和最低平均成绩
public static void main(String[] args)
{
Scanner console = new Scanner (System.in);
int numStud, numGrade = 0, count = 0, count2 = 0;
double totalgrades = 0;
System.out.println("Enter number of students:");
numStud = console.nextInt();
System.out.println("Enter number of student grades:");
numGrade = console.nextInt();
String[] students = new String [numStud];
double [][] grades = new double [numStud][numGrade];
double[] average = new double[numStud];
String x = console.nextLine();
System.out.println("");
while(count<numStud)
{
System.out.println("Enter name of student " + (count + 1) + ":");
students[count] = console.nextLine();
System.out.println("Enter " + numGrade + " grades:");
while(count2<numGrade)
{
grades[count][count2] = console.nextDouble();
totalgrades = totalgrades + grades [count][count2];
count2++;
}
average[count] = totalgrades / numGrade;
totalgrades = 0;
String y = console.nextLine();
count2 = 0;
count++;
}
count = 0;
count2 = 0;
while(count<numStud)
{
System.out.println("The grades of " + students[count] + " are:");
while(count2<numGrade)
{
System.out.println(grades[count][count2] + " ");
count2++;
}
System.out.println("The average is " + average[count] + ".");
System.out.println("");
count2 = 0;
count++;
}
答案 0 :(得分:0)
假设所有平均成绩保持在average
数组中。然后,
Arrays.sort(average);
System.out.print("min = " + average[0] + ", max = " + average[average.length - 1]);
要填写average
,您必须:
for(int j = 0; j < grades.length; ++j) {
int sum = 0;
for(int i = 0; i < grades[j].length; ++i) sum += grades[j][i];
average[j] = sum / numGrade;
}
正确填写grades
数组。但我建议您将while
循环转换为for
循环。
答案 1 :(得分:0)
要查找 最高 :
max
设置为第一个元素(或0)max
max
max
在循环结束时,您将获得数组的最大值。
int max = Integer.MIN_VALUE;
for(int x=0; x<average.length; x++)
if(average[x] > max)
max = average[x];
要查找 最低 :
min
设置为第一个元素(或0)min
min
min
在循环结束时,您将获得该数组的最小值。
int min = Integer.MAX_VALUE;
for(int x=0; x<average.length; x++)
if(average[x] < min)
min = average[x];