2016-04-23 56 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