C 語言模式程式



在統計數學中,眾數是一個出現次數最多的值。

例如 − 假設一組值 3、5、2、7、3。該值集合的眾數為 3,因為它的出現次數比任何其他數字都多。

演算法

我們可以推匯出一個演算法來查詢眾數,如下所示 −

START
   Step 1 → Take an integer set A of n values
   Step 2 → Count the occurence of each integer value in A
   Step 3 → Display the value with highest occurence
STOP

虛擬碼

我們可以使用上述演算法推匯出虛擬碼,如下所示 −

procedure mode()
   
   Array A
   FOR EACH value i in A DO
      Set Count to 0
      FOR j FROM 0 to i DO
         IF A[i] = A[j]
            Increment Count
         END IF
      END FOR
      
      IF Count > MaxCount
         MaxCount =  Count
         Value    =  A[i]
      END IF
   END FOR
   DISPLAY Value as Mode
   
end procedure

實現

該演算法的實現如下 −

#include <stdio.h>

int mode(int a[],int n) {
   int maxValue = 0, maxCount = 0, i, j;

   for (i = 0; i < n; ++i) {
      int count = 0;
      
      for (j = 0; j < n; ++j) {
         if (a[j] == a[i])
         ++count;
      }
      
      if (count > maxCount) {
         maxCount = count;
         maxValue = a[i];
      }
   }

   return maxValue;
}

int main() {
   int n = 5;
   int a[] = {0,6,7,2,7};

   printf("Mode = %d ", mode(a,n));

   return 0;
}

輸出

該程式的輸出應為 −

Mode = 7
mathematical_programs_in_c.htm
廣告
© . All rights reserved.