3

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

输出

从此处显示的方法获取 PI 3.14159265358979000000 从 .NET Math 类常量中获取 PI 3.14159265358979000000

4

1 回答 1

5

好吧,doubledecimal

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

于 2011-05-05T18:52:43.273 回答