[英]How would I calculate the average in a 2D Array?
首先,我对 Java 并不完全陌生,并且我已经参加过这方面的课程。 最近,一年后我再次拿起它,我对如何计算二维整数数组的平均值有点困惑。 例如,这是一段不包括平均计算的代码摘录:
//Program fills array with x students and their corresponding test grades for n amount of tests
System.out.println("Amount of students?");
int numstudents = sc.nextInt();
System.out.println("Amount of tests?");
int numtests = sc.nextInt();
int[][] marks = new int [numstudents][numtests];
int[] average = new int [numstudents];
for (int i = 0; i < numstudents; i++) {
for (int j = 0; j < numtests; j++) {
System.out.println("Enter the mark for student " + (i+1) + " on test " + (j+1));
marks[i][j] = sc.nextInt();
//Array is filled with grades.
}
}
现在假设我想计算每个学生的平均值并将值存储在average[]
数组中。 我的主要问题是弄清楚如何循环它,以便它包含对marks[0][j]
的每个测试,然后转到marks[1][j]
等等。 如果我执行以下代码之类的操作,它将获取每个测试值并将其除以numtests
。
for (int i = 0; i < numstudents; i++) {
for (int j = 0; j < numtests; j++) {
average[i] = marks[i][j]/numtests;
System.out.println("The average is " + average[i]);
}
}
我认为应该计算平均[i]
for (int i = 0; i < numstudents; i++) {
//here
for (int j = 0; j < numtests; j++) {
}
编写如下代码怎么样?
int eachsum = 0;
for (int i = 0; i < numstudents; i++) {
for (int j = 0; j < numtests; j++) {
eachsum += marks[i][j];
}
average[i] = eachsum/numtests;
System.out.println("The average for student " + (i+1) + " is " + average[i]);
eachsum = 0;
}
您可以执行以下操作:
int[] average = Arrays.stream(marks)
.map(ints -> Arrays.stream(ints).summaryStatistics().getAverage())
.mapToLong(Math::round)
.mapToInt(Math::toIntExact)
.toArray();
输入:
int[][] marks = {
{80, 70 ,90},
{90, 65 ,90},
{50, 70 ,70},
{80, 75 ,85}
};
Output:
[80,
82,
63,
80]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.