📜  Pi(Π)的值,最多50个小数位

📅  最后修改于: 2021-04-29 13:30:25             🧑  作者: Mango

给定数字N (其中N <= 50),任务是查找Pi( Π )的值,最多N个小数位。
例子:

方法:

1.使用acos()函数计算Π的值,该函数返回[-Π,Π]之间的数值。

2.由于使用acos(0.0)将返回2 *Π的值。因此得到Π的值:

double pi = 2*acos(0.0);

3.现在,从上述等式获得的值估计为N个十进制数字,如下所示:

printf("%.*lf\n", N, pi);

下面是上述方法的实现:

C++
// C++ program to calculate the
// value of pi up to n decimal
// places
#include "bits/stdc++.h"
using namespace std;
 
// Function that prints the
// value of pi upto N
// decimal places
void printValueOfPi(int N)
{
 
    // Find value of pi upto
    // using acos() function
    double pi = 2 * acos(0.0);
 
    // Print value of pi upto
    // N decimal places
    printf("%.*lf\n", N, pi);
}
 
// Driver Code
int main()
{
    int N = 45;
 
    // Function that prints
    // the value of pi
    printValueOfPi(N);
    return 0;
}


Java
// Java program to calculate the
// value of pi up to n decimal places
class GFG {
     
    // Function that prints the
    // value of pi upto N
    // decimal places
    static void printValueOfPi(int N)
    {
     
        // Find value of pi upto
        // using acos() function
        double pi = 2 * Math.acos(0.0);
     
        // Print value of pi upto
        // N decimal places
        System.out.println(pi);
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        int N = 4;
     
        // Function that prints
        // the value of pi
        printValueOfPi(N);
    }
}
 
// This code is contributed by AnkitRai01


Python3
# Python3 program to calculate the
# value of pi up to n decimal places
from math import acos
 
# Function that prints the
# value of pi upto N
# decimal places
def printValueOfPi(N) :
 
    # Find value of pi upto
    # using acos() function
    b = '{:.' + str(N) + 'f}'
    pi= b.format(2 * acos(0.0))
      
     
    # Print value of pi upto
    # N decimal places
    print(pi);
 
# Driver Code
if __name__ == "__main__" :
 
    N = 43;
 
    # Function that prints
    # the value of pi
    printValueOfPi(N);
     
# This code is contributed by AnkitRai01


C#
// C# program to calculate the
// value of pi up to n decimal places
using System;
 
class GFG {
     
    // Function that prints the
    // value of pi upto N
    // decimal places
    static void printValueOfPi(int N)
    {
     
        // Find value of pi upto
        // using acos() function
        double pi = 2 * Math.Acos(0.0);
     
        // Print value of pi upto
        // N decimal places
        Console.WriteLine(pi);
    }
     
    // Driver Code
    public static void Main()
    {
        int N = 4;
     
        // Function that prints
        // the value of pi
        printValueOfPi(N);
    }
}
 
// This code is contributed by AnkitRai01


输出:
3.1416

时间复杂度: O(1)