[英]How do I to print out the average of each row of a 2D array separately?
The assignment I have is to find the average of the temps in each row of the array.我的任务是找到数组每一行中温度的平均值。 There are 3 rows.
有 3 行。 I have to find the average of the 3 rows separately, not together, and then print out the averages like so:
我必须分别找到 3 行的平均值,而不是一起,然后像这样打印出平均值:
Avg for student 1 is x
Avg for students 2 is A
Avg for student 3 is h.
This is the actual assignment paper:这是实际的作业纸:
Name this program
testScoresArray
.将此程序
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!
提示:您需要跟踪分数,但每次遍历一列并找到平均值后,您需要将分数的值设置回 0 否则它将计算以前的分数!
EXAMPLE:
例子:
Average temp for Student 1: 91.0 Average temp for Student 2: 83.75 Average temp for Student 3: 96.0
This is the code I have right now.这是我现在拥有的代码。 I need to find a way to find the averages separately and print them the way above.
我需要找到一种方法来分别找到平均值并按照上面的方式打印它们。 I can't seem to do that.
我似乎不能这样做。 Can anyone help me, please?
任何人都可以帮助我吗?
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();
}
}
}
Not the best, but the easiest solution would be to simply change the type of sum to float or double不是最好的,但最简单的解决方案是简单地将 sum 的类型更改为 float 或 double
float sum = 0;
This will make the division that happens on the println to change from integer division to a floating point one, if only one of the operands has a floating point then your print will have a dot这将使 println 上发生的除法从 integer 除法更改为浮点除法,如果只有一个操作数有浮点,那么您的打印将有一个点
Single-semicolon solution using streams:使用流的单分号解决方案:
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);
Output: Output:
Average temp for Student 1: 91.0
Average temp for Student 2: 83.75
Average temp for Student 3: 96.0
See also: Searching for average temperature for all dates between two dates另请参阅:搜索两个日期之间所有日期的平均温度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.