开发者

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

开发者 https://www.devze.com 2023-03-03 10:20 出处:网络
With reg to this question Pi in C# I coded the below code and gives a output with last 6 digits as 0. So I want to improve the program by converting everything to decimal. I have never used decimal i

With reg to this question Pi in C#

I coded the below code and gives a output with last 6 digits as 0. So I want to improve the program by converting everything to decimal. I have never used decimal in C# instead of a double before and I am only comfortable with double in my regular use.

So please help me with decimal conversion, i tried to replace all double to decimal at start and it didnt turn good :(.

 using System;

class Program
{
    static void Main()
    {
    Console.Wri开发者_JAVA百科teLine(" 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 shown here 3.14159265358979000000 Get PI from the .NET Math class constant 3.14159265358979000000


Well, replacing double with decimal is a good start - and then all you need to do is change the constant from 2.0 to 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);
    }
}

Of course it's still going to have limited precision, but slightly more than double. The result is 3.14159265358979325010.

0

精彩评论

暂无评论...
验证码 换一张
取 消