Java 如何计算二维阵列中的平均值?
首先,我对Java并不完全陌生,我已经上了一门Java课程。最近,我在一年后再次拿起它,对于如何计算二维整数数组中的平均值,我有点困惑。例如,下面是不包括平均计算的代码摘录:Java 如何计算二维阵列中的平均值?,java,arrays,loops,for-loop,integer,Java,Arrays,Loops,For Loop,Integer,首先,我对Java并不完全陌生,我已经上了一门Java课程。最近,我在一年后再次拿起它,对于如何计算二维整数数组中的平均值,我有点困惑。例如,下面是不包括平均计算的代码摘录: //Program fills array with x students and their corresponding test grades for n amount of tests System.out.println("Amount of students?"); int nu
//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.
}
}
我认为应该计算平均值
for (int i = 0; i < numstudents; i++) {
//here
for (int j = 0; j < numtests; j++) {
}
for(int i=0;i
编写如下代码怎么样
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-eachsum=0;
对于(int i=0;i
您可以执行以下操作:
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}
};
输出:
[80,
82,
63,
80]
[80,
82,
63,
80]