2016-12-15 51 views
-2

正數和負數二維數組的總和平均值如何找到在C與正數和負數二維數組的總和平均我如何才能找到在C

int data[4][5] = { 
    {3,-6,1,-5,7}, 
    {-2,9,-3,5,4}, 
    {7,3,-4,0,-6}, 
    {9,-2,-5,8,3} 
}; 

>Sum of all positive number 
>Mean of all positve number 
>Sum of all negative number 
>Mean of all negative number 

我從念大一我明天有期末考試,請幫助我練習。謝謝!

+1

掃描整個數組if(a [i] [j]> 0),找到它們的總和並跟蹤總正數。除以總額。對於負數也是如此。 – lU5er

+0

你可以給我解釋我的代碼,請先生。 – Tony

+0

@RoadRunner謝謝你,我會爲它做更多的事情,但LP有什麼問題我在這篇文章中做了什麼錯誤,如果錯了,我會刪除它 – Tony

回答

1

下面是一些在1D數組上工作的代碼。你可以理解這一點,並將其應用於你的2D問題。

我們需要變量來跟蹤兩個總和(正數和負數),它們可以是int s。我們需要兩個變量來計算陣列中有多少個正數和負數,這些變量也可以是int s。那麼我們需要兩個變量來存儲平均值。這些可能是float s,但是最好使用double來進行這種計算。最後,我們需要一個變量來索引數組。我通常使用size_t變量來處理這類事情,但在這裏我將使用另一個int

在循環遍歷數組以找到總數和計數值之後,該計算平均值了。一個陷阱要提防這裏是所有的參數都是int型的,所以如果我們計算:

mean_pos = sum_pos/count_pos; 

,我們將利用整數除法,並失去了結果的小數部分。我們可以乘以count_pos * 1.0將此值轉換爲double並使用浮點除法。

我應該指出,這段代碼不會計入零值,這就是您的問題規範所建議的。如果你想用其中一種方法計算0(它們不是正數或負數),修改代碼應該是一件簡單的事情。

祝您好運,您的測試。

#include <stdio.h> 

int main(void) 
{ 
    int data[10] = { 3, -6, 1, -5, 7, -2, 9, -3, 5, 4 }; 
    int sum_pos = 0; 
    int sum_neg = 0; 
    int count_pos = 0; 
    int count_neg = 0; 
    double mean_pos, mean_neg; 
    int i; 

    for (i = 0; i < 10; i++) { 
     if (data[i] > 0) { 
      sum_pos += data[i]; 
      ++count_pos; 
     } else if (data[i] < 0) { 
      sum_neg += data[i]; 
      ++count_neg; 
     } 
    } 

    mean_pos = sum_pos/(count_pos * 1.0); 
    mean_neg = sum_neg/(count_neg * 1.0); 

    printf("Sum of positive numbers: %d\n", sum_pos); 
    printf("Mean of positive numbers: %f\n", mean_pos); 
    printf("Sum of negative numbers: %d\n", sum_neg); 
    printf("Mean of negative numbers: %f\n", mean_neg); 

    return 0; 
} 
+0

非常感謝你! ,我會從中吸取教訓, – Tony

0
#include <stdio.h> 
#include <stdlib.h> 

#define ROWS 4 
#define COLS 5 

int 
main(void) { 
    int data[ROWS][COLS] = {{3,-6,1,-5,7}, 
          {-2,9,-3,5,4}, 
          {7,3,-4,0,-6}, 
          {9,-2,-5,8,3}}; 
    int numpos = 0, numneg = 0; 
    int possum = 0, negsum = 0; 
    int row, col; 

    for (row = 0; row < ROWS; row++) { 
     for (col = 0; col < COLS; col++) { 
      if (data[row][col] > 0) { 
       possum += data[row][col]; 
       numpos++; 
      } else if (data[row][col] < 0) { 
       negsum += data[row][col]; 
       numneg++; 
      } 
     } 
    } 

    printf("Sum of all positive numbers = %d\n", possum); 
    printf("Mean of all positive numbers = %.2f\n", ((1.0) * possum)/numpos); 
    printf("Sum of all negative numbers = %d\n", negsum); 
    printf("Mean of all negative numbers = %.2f\n", ((1.0) * negsum)/numneg); 

    return 0; 
} 
+0

不要餵動物.... – LPs

+0

非常感謝你! – Tony

+0

我做到了......;) – LPs