如何在c#程序中得到圆周率的小数到n位精度

本文关键字:圆周率 小数 精度 程序 | 更新日期: 2023-09-27 17:54:53

关于这个问题c#中的Pi

我编写了下面的代码,并给出了最后6位数字为0的输出。所以我想通过把所有东西都转换成十进制来改进这个程序。我以前从来没有在c#中使用过十进制而不是双精度,我只在我的常规使用中使用双精度。

所以请帮助我与十进制转换,我试图取代所有的双十进制开始,它没有好转:(。

 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);
    }
    }
}

输出

从这里显示的方法获取PI3.14159265358979000000从。net Math类常量中获取PI3.14159265358979000000

如何在c#程序中得到圆周率的小数到n位精度

嗯,用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);
    }
}

当然,它仍然会有有限的精度,但略高于double。结果为3.14159265358979325010