How to get decimal to n places accuracy in C # program for Pi

From reg to this question Pi in C #

I encoded the code below and returned the result with the last 6 digits as 0. Therefore, I want to improve the program by converting everything to decimal. I have never used a decimal in C # instead of a double before, and I'm just comfortable with a double in my normal use.

So, please help me with the decimal conversion, I tried to replace everything double with decimal at the start, and it did not become good :(.

 using System;

class Program
{
    static void Main()
    {
    Console.WriteLine(" Get PI from methods shown here");
    double d = PI();
    Console.WriteLine("{0:N20}",
        d);

    Console.WriteLine(" Get PI from the .NET Math class constant");
    double d2 = Math.PI;
    Console.WriteLine("{0:N20}",
        d2);
    }

    static double PI()
    {
    // Returns PI
    return 2 * F(1);
    }

    static double F(int i)
    {
    // Receives the call number
   //To avoid so error
    if (i > 60)
    {
        // Stop after 60 calls
        return i;
    }
    else
    {
        // Return the running total with the new fraction added
        return 1 + (i / (1 + (2.0 * i))) * F(i + 1);
    }
    }
}

Output

Get PI from methods given here 3.14159265358979000000 Get PI from .NET Math class constant +3.14159265358979000000

+3
source share
1 answer

, double decimal - - , , 2.0 2.0m:

static decimal F(int i)
{
    // Receives the call number
    // To avoid so error
    if (i > 60)
    {
        // Stop after 60 calls
        return i;
    }
    else
    {
        // Return the running total with the new fraction added
        return 1 + (i / (1 + (2.0m * i))) * F(i + 1);
    }
}

, , , double. 3.14159265358979325010.

+4

All Articles