编写程序以查找前N个自然数的平均值。
例子:
Input : 10
Output : 5.5
1+2+3+4+5+6+7+8+9+10 = 5.5
Input : 7
Output : 4.0
1+2+3+4+5+6+7 = 4
先决条件:前n个自然数之和。
如前所述,n个自然数的总和n(n + 1)/ 2,我们发现n个自然数的平均值,因此除以n为n(n + 1)/ 2 * n =(n + 1)/ 2。如果第一项为1,则n为最后一项。
C++
// CPP Program to find the Average of first
// n natural numbers
#include
using namespace std;
// Return the average of first n natural numbers
float avgOfFirstN(int n)
{
return (float)(1 + n)/2;
}
// Driven Program
int main()
{
int n = 20;
cout << avgOfFirstN(n) << endl;
return 0;
}
Java
// Java Program to find the Average of first
// n natural numbers
import java.io.*;
class GFG {
// Return the average of first n
// natural numbers
static float avgOfFirstN(int n)
{
return (float)(1 + n) / 2;
}
// Driven Program
public static void main(String args[])
{
int n = 20;
System.out.println(avgOfFirstN(n));
}
}
/*This code is contributed by Nikita tiwari.*/
Python3
# Python 3 Program to find the Average
# of first n natural numbers
# Return the average of first n
# natural numbers
def avgOfFirstN(n) :
return (float)(1 + n) / 2;
# Driven Program
n = 20
print(avgOfFirstN(n))
# This code is contributed by Nikita Tiwari.
C#
// C#Program to find the Average of first
// n natural numbers
using System;
class GFG {
// Return the average of first n
// natural numbers
static float avgOfFirstN(int n)
{
return (float)(1 + n) / 2;
}
// Driven Program
public static void Main()
{
int n = 20;
Console.WriteLine(avgOfFirstN(n));
}
}
/*This code is contributed by vt_m.*/
PHP
Javascript
输出:
10.5
时间复杂度:O(1)