2011-05-05 84 views
3

具有reg这个问题 Pi in C#如何获得小数n位精度在C#程序丕

我编写了下面的代码,并给出了最后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); 
    } 
    } 
} 

输出

点击此处显示为从PI方法从.NET Math类常量 3.14159265358979000000获取PI 3.14159265358979000000

+0

查看Eric Lippert的一个非常类似的问题的答案:http://stackoverflow.com/questions/4107047/c-high-double-precision/4107225#4107225 – Justin 2011-05-05 18:54:45

+0

@Justin,我不想改变算法到埃里克的。我对此感到满意。 – 2011-05-05 19:20:26

回答

4

那么,与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

+0

请您介绍一下Jon Skeet解决方案的算法。 – user2922935 2016-02-22 02:57:04

+0

@ user2922935:它与原始代码的算法相同。我所做的一切就是使'decimal'一致。 – 2016-02-22 06:44:14