C 语言中的平均值程序



平均数是给定数字集合的平均值。它的计算方法类似于平均值。将所有给定数字相加,然后除以总数字,得到平均数

例如 - 3、5、2、7、3 的平均数为 (3 + 5 + 2 + 7 + 3) / 5 = 4

算法

我们可以按以下步骤绘制其算法 −

START
   Step 1 → Take an integer set A of n values
   Step 2 → Add all values of A together
   Step 3 → Divide result of Step 2 by n
   Step 4 → Result is mean of A's values
STOP

伪代码

现在我们为上述算法编写伪代码。

procedure mean()
   
   Array A
   FOREACH value i of A DO
      sum = sum + i
   ENDFOR
   MEAN = sum / n

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() {
   float mean;
   int sum, i;
   int n = 5;
   int a[] = {2,6,7,4,9};

   sum = 0;

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

   printf("Mean = %f ", sum/(float)n);

   return 0;
}

输出

程序的输出应为 −

Mean = 5.600000
mathematical_programs_in_c.htm
广告