[英]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.