[英]find average of columns of a 2d jagged array
I am trying to find the averages of columns of a jagged array but I get an error saying that arr[j].length
when I'm dividing it by the sum, the j
cannot find symbol.我试图找到一个锯齿状数组的列的平均值,但是当我将它除以总和时,我得到一个错误,说
arr[j].length
, j
找不到符号。 What can I do to fix this problem?我能做些什么来解决这个问题?
int maxC = arr[0].length;
for (int a = 1; a < arr.length; a++){
if (arr[a].length > maxC){
maxC = arr[a].length;
}
}
for (int i = 0; i < maxC; i++){
double sum = 0.0;
for (int j = 0; j < arr.length; j++){
if (i < arr[j].length){
sum += arr[j][i];
}
}
double avg = sum / arr[j].length;
System.out.println("Average of col " + (i + 1) + "is: " + avg);
}
Your variable j
is declared in the inner for loop.您的变量
j
在内部 for 循环中声明。 Outside of that loop it does not exist.在该循环之外它不存在。 But the way I see it, you don't want to divide by the length of
arr[j]
, but by the number of numbers you added.但在我看来,你不想除以
arr[j]
的长度,而是除以你添加的数字数量。 That's arr.length
minus the number of nested arrays that are too short.这是
arr.length
减去太短的嵌套 arrays 的数量。
The easiest way to fix this is to introduce a new variable that you increment inside your if statement, then divide by that variable instead of by arr[j].length
.解决此问题的最简单方法是在 if 语句中引入一个新变量,然后除以该变量而不是
arr[j].length
。
It might be better to use row
/ col
names instead of common i
/ j
to improve code clarity.使用
row
/ col
名称而不是常见的i
/ j
可能会更好地提高代码清晰度。 Also, a separate counter for the columns is needed to increment only when a column is present in a row to properly calculate the average:此外,仅当行中存在列以正确计算平均值时,才需要为列增加一个单独的计数器:
for (int col = 0; col < maxC; col++) {
double sum = 0.0;
int colCount = 0;
for (int row = 0; row < arr.length; row++) {
if (col < arr[row].length) {
sum += arr[row][col];
colCount++;
}
}
double avg = sum / colCount;
System.out.println("Average of col #" + (col + 1) + " is: " + avg);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.