如何分别打印出二维数组每一行的平均值?

How do I to print out the average of each row of a 2D array separately?

我的任务是找出数组每一行的温度平均值。有3行。我必须分别求出 3 行的平均值,而不是一起求平均值,然后像这样打印出平均值:

Avg for student 1 is x
Avg for students 2 is A
Avg for student 3 is h.

这是实际的作业论文:

Name this program testScoresArray. Write a program that stores the following temps in a 2D array.

Student 1: 100, 80, 93
Student 2: 74, 83, 91, 87
Student 3: 94, 98

Find the average temp for EACH student separately. Hint: you need to keep track of the score but after every time it loops through a column and finds the average, you need to set the value of the score back to 0 or it will count the previous scores!

EXAMPLE:

Average temp for Student 1: 91.0
Average temp for Student 2: 83.75
Average temp for Student 3: 96.0 

这是我现在拥有的代码。我需要找到一种方法来分别找到平均值并按照上面的方式打印它们。我好像做不到。有谁能帮帮我吗?

public class testScoresArray {
    public static void main(String args[]) {
        int[][] temps = {{100, 80, 93}, {74, 83, 91, 87}, {94, 98}};
        for (int i = 0; i < temps.length; i++) {
            int sum = 0;
            for (int g = 0; g < temps[i].length; g++) {
                sum += temps[i][g];
            }
            System.out.println(sum / temps[i].length);
            System.out.println();
        }
    }
}

不是最好的,但最简单的解决方案是简单地将求和类型更改为 float 或 double

float sum = 0;

这将使 println 上发生的除法从整数除法变为浮点除法,如果只有一个操作数具有浮点数,那么您的打印将有一个点

使用流的单分号解决方案:

int[][] temps = {{100, 80, 93}, {74, 83, 91, 87}, {94, 98}};
// iterating over row indices
IntStream.range(0, temps.length)
        // print the beginning of each row
        .peek(i -> System.out.print("Average temp for Student "+(i+1)+": "))
        // take the average of the row
        .mapToDouble(i -> Arrays.stream(temps[i]).average().orElse(0.0))
        // print the average value and the line break
        .forEach(System.out::println);

输出:

Average temp for Student 1: 91.0
Average temp for Student 2: 83.75
Average temp for Student 3: 96.0

另请参阅: