0

我想找出行和平均值,但如果行中出现零,那么当行的平均值完成时,应该保留该特定列。让它更清楚。我有一个矩阵说

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

请指导我哪里做错了

4

3 回答 3

0

您的if(hostmatrix[j]==0)支票没有考虑该行。结果,每次到达第 5 列时,它都在第一行,并且看到零。

于 2016-04-23T12:30:47.127 回答
0

下面的代码应该解决这个问题。问题是您的内部循环没有正确迭代。我将其更改为索引到数组中的正确位置。让我知道它是否有效!

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++){

        //the problem was here
        if(hostMatrix[i * cols + j] != 0){
            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]);
}
于 2016-04-23T12:33:08.203 回答
0

编辑以下行:

if(hostMatrix[j]==0)

它应该是:

if(hostMatrix[i][j]==0)

这样它就不会保留在第一行并始终找到 0。

于 2016-04-23T12:37:51.110 回答