Home > Backend Development > C++ > body text

Mean square of natural numbers?

WBOY
Release: 2023-09-20 22:29:12
forward
1488 people have browsed it

Mean square of natural numbers?

The average of the squares of natural numbers is calculated by adding all the squares of n natural numbers and then dividing by that number.

Example

The first 2 natural numbers are 2.5,

12 22 = 5 => 5/2 = 2.5.

There are two calculation methods in programming -

  • Use loops
  • Use formulas
Use loops to calculate squares of natural numbers The average of

This logic works by finding the square of all natural numbers. Find the square of each by looping from 1 to n and add to the sum variable. Then divide that sum by n.

Program for calculating the sum of squares of natural numbers -

Sample code

Real-time demonstration

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

Output

The average of the square of 2 natural numbers is 2.500000
Copy after login
Copy after login

Use the formula to calculate the mean of the squares of natural numbers.

There are mathematical formulas to make calculations easy. To calculate the sum of squares of natural numbers, the formula is ' n*(n 1)*((2*n) 1)/6' Divide it by the number n to get the formula: ' (n 1)* ((2*n) 1 )/6'.

Program for finding the sum of squares of natural numbers -

Sample code

Live demonstration< /p>

#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;
}
Copy after login

Output

The average of the square of 2 natural numbers is 2.500000
Copy after login
Copy after login

The above is the detailed content of Mean square of natural numbers?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!