AI编程助手
AI免费问答

自然数的平方平均值?

WBOY   2023-09-20 22:29   1826浏览 转载

自然数的平方平均值?

自然数平方的平均值是通过将 n 个自然数的所有平方相加,然后除以该数字来计算的。

示例

前 2 个自然数为 2.5 ,

12 + 22 = 5 => 5/2 = 2.5。

编程中有两种计算方法 -

  • 使用循环
  • 使用公式
使用循环计算自然数平方的平均值

此逻辑通过查找所有自然数的平方来工作。通过从 1 到 n 循环找到每个的平方并添加到 sum 变量。然后将该总和除以 n。

计算自然数平方和的程序 -

示例代码

 实时演示

#include <stdio.h>
int main() {
   int n = 2;
   float sum = 0;
   for (int i = 1; i <h2>输出</h2>
<pre class="brush:php;toolbar:false;">The average of the square of 2 natural numbers is 2.500000

使用公式计算自然数的平方平均值。 

有数学公式可以使计算变得容易。为了计算自然数的平方和,公式为 ' n*(n+1)*((2*n)+1)/6' 将其除以数字 n 得到公式: ' (n+1)* ((2*n)+1)/6'。

求自然数平方和的程序 -

示例代码

 现场演示

#include <stdio.h>
int main() {
   int n = 2;
   float average = ((n+1)*((2*n)+1)/6);
   printf("The average of the square of %d natural numbers is %f", n,average);
   return 0;
}</stdio.h>

输出

The average of the square of 2 natural numbers is 2.500000
声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除