【问题标题】:How to get decimal to n places precision in C# program for Pi如何在 Pi 的 C# 程序中将小数点精确到 n 位
【发布时间】:2011-05-05 18:50:28
【问题描述】:

注册这个问题 Pi in 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 3.14159265358979000000 从.NET Math类常量中获取PI 3.14159265358979000000

【问题讨论】:

标签: c# decimal precision pi


【解决方案1】:

嗯,用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

【讨论】:

  • 请您解释一下 Jon Skeet 解决方案的算法。
  • @user2922935:与原始代码的算法相同。我所做的就是使用一致的decimal
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多