我想找出行和平均值,但如果行中出现零,那么当行的平均值完成时,应该保留该特定列。让它更清楚。我有一个矩阵说
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
请指导我哪里做错了