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

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

实现

该算法的实现如下 -

#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
广告