我想找出行总和的平均值,但是如果行中出现零,那么当该行的平均值完成时应该保留该特定列。让它更清楚。我有一个矩阵说行平均值:元素在比较时似乎为零
5 3 4 4 0
3 1 2 3 3
4 3 4 3 5
3 3 1 5 4
1 5 5 2 1
行总的平均第一行应该是16/4,而不是16/5,因为我们离开第1行5列,因为它含有“0”值
我试图以下代码。对于第一行它的工作正常,但对于其余的每一行2-5行,并且每一列5将其值留下,尽管其不为零。
我的代码是:我接受该计划
int rows = 5;
int cols = 5;
float hostMatrix[] = createExampleMatrix(rows, cols);
System.out.println("Input matrix:");
System.out.println(createString2D(hostMatrix, rows, cols));
float sums[] = new float[rows];
for(int i=0;i<rows;i++){
float sum = 0,counter=0;
for(int j=0;j<cols;j++){
if(hostMatrix[j]==0){
sum += hostMatrix[i * cols + j];
}
else
{
sum += hostMatrix[i * cols + j];
counter++;
}
}
sum=sum/counter;
sums[i] = sum;
}
System.out.println("sums of the columns ");
for(int i=0;i<rows;i++){
System.out.println(" "+sums[i]);
}
输出为:
sums of the columns
4.0
3.0
4.75
4.0
3.5
我想作为输出:
4.0
2.4
3.8
3.2
2.8
请指导我在哪里,我在做什么错误
随着你阵列中的每一行,你总是在'if'的条件中检查'hostMatrix [j] == 0',当'j = 4',当然''hostMatrix [4] == 0'在你的数组中。你可以尝试下面的'nhouser9'的回答来修正,或者简单地把if(hostMatrix [j] == 0)'改成'if(hostMatrix [i * cols + j] == 0)'。 –