PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

给定的偶数之前的所有偶数的平均值是多少?

王林
王林 转载
2023-08-25 23:53:06 624浏览

给定的偶数之前的所有偶数的平均值是多少?

为了找到给定偶数之前的偶数的平均值,我们将把给定数字之前的所有偶数相加,然后计算偶数的数量。然后将总和除以偶数的个数。

示例

直到 10 为止偶数的平均值为 6,即

2 + 4 + 6 + 8 + 10 = 30 => 30/ 5 = 6

有两种方法计算直到 n 的偶数的平均值,即 偶数。

  • 使用循环
  • 使用公式

计算直到n为止偶数的平均值的程序使用循环

为了计算直到n的偶数的平均值,我们将把直到n的所有偶数相加,然后除以直到n的偶数的个数。

计算程序直到 n 为止的偶自然数的平均值 -

示例代码

实时演示

#include <stdio.h>
int main() {
   int n = 14,count = 0;
   float sum = 0;
   for (int i = 1; i <= n; i++) {
      if(i%2 == 0) {
         sum = sum + i;
         count++;
      }
   }
   float average = sum/count;
   printf("The average of even numbers till %d is %f",n, average);
   return 0;
}

输出

The average of even numbers till 14 is 8.000000

使用公式计算直到 n 的偶数的平均值

要计算直到 n 的偶数的平均值,我们可以使用数学公式 (n+2)/2,其中 n 是偶数这是我们问题中的给定条件。

计算 n 个偶自然数平均值的程序 -

示例代码

实时演示

#include <stdio.h>
int main() {
   int n = 15;
   float average = (n+2)/2;
   printf("The average of even numbers till %d is %f",n, average);
   return 0;
}

输出

The average of even numbers till 14 is 8.000000

以上就是给定的偶数之前的所有偶数的平均值是多少?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除