2016-04-23 66 views
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 

请指导我在哪里,我在做什么错误

+0

随着你阵列中的每一行,你总是在'if'的条件中检查'hostMatrix [j] == 0',当'j = 4',当然''hostMatrix [4] == 0'在你的数组中。你可以尝试下面的'nhouser9'的回答来修正,或者简单地把if(hostMatrix [j] == 0)'改成'if(hostMatrix [i * cols + j] == 0)'。 –

回答

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]); 
} 
0

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

+0

我试过http://stackoverflow.com/questions/5269183/how-to-compare-integer-with-integer-array但它不工作在我的情况下 – user3804161

0

编辑下面一行:

if(hostMatrix[j]==0) 

它应该是:

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

所以它不会停留在第一行上,并总能找到一个0

+0

他正在使用一维数组。修复'if'条件:'if(hostMatrix [i * cols + j] == 0)' –

+0

@dang Khowa ..你解决了我的问题..thanx – user3804161