📌  相关文章
📜  程序查找1/1 /系列的总和! + 2/2! + 3/3! + 4/4! +……。+ n / n!

📅  最后修改于: 2021-05-05 01:49:54             🧑  作者: Mango

您获得了1/1系列! + 2/2! + 3/3! + 4/4! +……。+ n / n !,找出直到第n个项的序列之和。
例子 :

Input :n = 5
Output : 2.70833

Input :n = 7
Output : 2.71806

一个简单的解决方案是一一对应的计算机术语。对于每个术语,请找到其对应的阶乘值。
一个有效的解决方案是在同一循环中进行阶乘计算。

CPP
// CPP program to print
// the sum of series
#include
using namespace std;
 
// function to calculate
// sum of given series
double sumOfSeries(double num)
{
    double res = 0, fact = 1;
    for (int i = 1; i <= num; i++)
    {
        // fact variable store
        // factorial of the i
        fact = fact * i;
 
        res = res + (i / fact);
    }
    return(res);
}
 
// Driver Code
int main()
{
    double n = 5;
    cout << "Sum: " << sumOfSeries(n);
    return 0;
}


Java
// Java program to print
// the sum of series
 
import java.io.*;
import java.lang.*;
 
class GFG
{
    public static double sumOfSeries(double num)
    {
        double res = 0, fact = 1;
        for (int i = 1; i <= num; i++)
        {
            // fact variable store
            // factorial of the i
            fact = fact * i;
 
            res = res + (i / fact);
        }
        return(res);
    }
 
    // Driver Code
    public static void main (String[] args)
    {
        double n = 5;
        System.out.println("Sum: " + sumOfSeries(n));
    }
}
 
// This code is contributed by
// Mohit Gupta_OMG <(0_o)>


Python3
# Python code to find smallest K-digit 
# number divisible by X
 
def sumOfSeries(num):
     
    # Computing MAX
    res = 0
    fact = 1
     
    for i in range(1, num+1):
        fact *= i
        res = res + (i/ fact)
         
    return res
     
 
n = 5
print("Sum: ", sumOfSeries(n))
 
# Code contributed by
# Mohit Gupta_OMG <(0_o)>


C#
// C# program to print the sum of series
using System;
 
class GFG
{
    public static float sumOfSeries(double num)
    {
        float res = 0, fact = 1;
        for (int i = 1; i <= num; i++)
        {
            // fact variable store
            // factorial of the i
            fact = fact * i;
 
            res = res + (i / fact);
        }
        return(res);
    }
 
    // Driver Code
    public static void Main ()
    {
        double n = 5;
        Console.Write("Sum: " + sumOfSeries(n));
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:

Sum: 2.70833