我正在尝试计算行和列的平均值。所以,到目前为止,我可以获得列的平均值,但是,我很难计算行的平均值。
我有这样的数据表,
Example1 Example2 Example2
85 75 92
80 91 89
85 52 78
到目前为止,我所做的是将它们的每一列作为一个数组,如下所示:
int[] Example1 = {85, 80, 85};
int[] Example2 = {75, 91, 52};
int[] Example3 = {92, 89, 78};
然后我创建了一个这样的方法(计算表中每一列的平均值),
public static void avg_calc(int[] examples) {
int sum = 0;
int avg;
for (int i = 0; i < examples.length; i ++) {
sum += examples[i];
}
avg = sum/examples.length;
System.out.println("Average is " + avg);
}
这样,当我执行 avg_calc(Example1)
时,我可以计算“Example1”数组的平均值,即 83。
但是,我想计算 Example1
、Example2
和 Example3
的平均值,例如,第一行的平均值,这将84 岁。
如何在我的函数中添加另一个数组来计算行的平均值?
如有任何帮助,我们将不胜感激。
最佳答案
How can I add another array into my function to calculate the average for rows?
一种方法:
int[] Example1 = {85, 80, 85};
int[] Example2 = {75, 91, 52};
int[] Example3 = {92, 89, 78};
int[][] examples = {Example1, Example2, Example3}; // new array
for (int i = 0; i < examples[0].length; i++) {
double rowAverage = 0;
for (int[] arr : examples) {
rowAverage += arr[i];
}
System.out.println("Average of row " + (i + 1) + ": " + rowAverage / examples.length);
}
输出
Average of row 1: 84.0
Average of row 2: 86.66666666666667
Average of row 3: 71.66666666666667
关于java - Java中使用数组计算数据表中行的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46985199/