简体   繁体   English

如何在C#程序中获取小数到n位精度的Pi

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

With reg to this question Pi in C# 注册到C#中的Pi#

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. 我编写了下面的代码并给出了最后6位数为0的输出。所以我想通过将所有内容转换为十进制来改进程序。 I have never used decimal in C# instead of a double before and I am only comfortable with double in my regular use. 我从来没有在C#中使用过十进制而不是之前的双倍,而我在常规使用中只能使用double。

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.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 shown here 3.14159265358979000000 Get PI from the .NET Math class constant 3.14159265358979000000 从此处显示的方法获取PI 3.14159265358979000000从.NET Math类常量获取PI 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: 好吧,用decimal替换double是一个好的开始 - 然后你需要做的就是将常量从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);
    }
}

Of course it's still going to have limited precision, but slightly more than double . 当然它的精确度仍然有限​​,但略高于double The result is 3.14159265358979325010 . 结果是3.14159265358979325010

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM