📌  相关文章
📜  求出系列的总和1 + 1/3 + 1/5 + 1/7 +…直到N项

📅  最后修改于: 2021-04-27 06:01:52             🧑  作者: Mango

给定数字N ,任务是找到以下序列的和,直到N个项。

例子:

方法:从给定的系列中,找到第N个项的公式:

1st term = 1
2nd term = 1/3
3rd term = 1/5
4th term = 1/7
.
.
Nthe term = 1 / (2 * N - 1))

所以:

然后对[1,N]范围内的数字进行迭代以使用上述公式查找所有项并计算其总和。
下面是上述方法的实现:

C++
*** QuickLaTeX cannot compile formula:
 

*** Error message:
Error: Nothing to show, formula is empty


Java
// C++ program to find the sum of the
// series 1 + 1/3 + 1/5 + ...
 
#include 
using namespace std;
 
// Function to find the sum of the
// given series
void printSumSeries(int N)
{
    // Intialise the sum to 0
    float sum = 0;
 
    for (int i = 1; i <= N; i++) {
 
        // Generate the ith term and
        // add it to the sum
        sum += 1.0 / (2 * i - 1);
    }
 
    // Print the final sum
    cout << sum << endl;
}
 
// Driver Code
int main()
{
    int N = 6;
 
    printSumSeries(N);
    return 0;
}


Python3
// Java program to find the sum of the
// series 1 + 1/3 + 1/5 + ...
class GFG {
     
    // Function to find the sum of the
    // given series
    static void printSumSeries(int N)
    {
        // Intialise the sum to 0
        float sum = 0;
     
        for (int i = 1; i <= N; i++) {
     
            // Generate the ith term and
            // add it to the sum
            sum += 1.0 / (2 * i - 1);
        }
     
        // Print the final sum
        System.out.println(sum);
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        int N = 6;
     
        printSumSeries(N);
 
    }
     
}
 
// This code is contributed by AnkitRai01


C#
# Python3 program to find the sum of the
# series 1 + 1/3 + 1/5 + ...
 
# Function to find the sum of the
# given series
def printSumSeries(N) :
 
    # Intialise the sum to 0
    sum = 0;
 
    for i in range(1, N + 1) :
 
        # Generate the ith term and
        # add it to the sum
        sum += 1.0 / (2 * i - 1);
 
    # Print the final sum
    print(sum);
 
# Driver Code
if __name__ == "__main__" :
 
    N = 6;
 
    printSumSeries(N);
 
# This code is contributed by AnkitRai01


Javascript
// C# program to find the sum of the
// series 1 + 1/3 + 1/5 + ...
using System;
 
class GFG {
     
    // Function to find the sum of the
    // given series
    static void printSumSeries(int N)
    {
        // Intialise the sum to 0
        float sum = 0;
     
        for (int i = 1; i <= N; i++) {
     
            // Generate the ith term and
            // add it to the sum
            sum += (float)1.0 / (2 * i - 1);
        }
     
        // Print the final sum
        Console.WriteLine(sum);
    }
     
    // Driver Code
    public static void Main (string[] args)
    {
        int N = 6;
     
        printSumSeries(N);
    }   
}
 
// This code is contributed by AnkitRai01


输出: