C 中的平均值計算程式



一組數字的平均值是它們的總和除以它們的個數。可以將其定義為:

average = sum of all values / number of values

在這裡,我們將學習如何以程式設計的方式計算平均值。

演算法

該程式的演算法非常簡單 -

START
   Step 1 → Collect integer values in an array A of size N
   Step 2 → Add all values of A
   Step 3 → Divide the output of Step 2 with N
   Step 4 → Display the output of Step 3 as average
STOP

虛擬碼

讓我們為給定演算法編寫虛擬碼 -

procedure average()
   
   Array A
   Size  N
   FOR EACH value i of A
      sum ← sum + A[i]
   END FOR
   average = sum / N
   DISPLAY average
   
end procedure

實現

該演算法的實現如下 -

#include <stdio.h>

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

   total = 0;
   
   for(i = 0; i < n; i++) {
      total += a[i];
   }

   printf("Average = %f\n", total/(float)n);
   return 0;
}

輸出

程式的輸出應為:

Average = 4.800000
mathematical_programs_in_c.htm
廣告
© . All rights reserved.