c# - 如何在 Pi 的 C# 程序中将小数点精确到 n 位

标签 c# decimal precision pi

对于这个问题 Pi in C#

我编写了以下代码并给出了最后 6 位数字为 0 的输出。所以我想通过将所有内容转换为十进制来改进程序。我以前从未在 C# 中使用过 decimal 而不是 double,而且在我的常规使用中我只对 double 感到满意。

所以请帮我进行十进制转换,我试图在开始时将所有 double 替换为十进制,但结果并不好:(。

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

输出

Get PI from methods shown here 3.14159265358979000000 Get PI from the .NET Math class constant 3.14159265358979000000

最佳答案

好吧,将 double 替换为 decimal 是一个好的开始 - 然后您需要做的就是将常量从 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

关于c# - 如何在 Pi 的 C# 程序中将小数点精确到 n 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5902704/

相关文章:

c# - Windows 窗体设计器和通用窗体

c# - 正则表达式提取所有小数值并迭代

MySQL:从 double 转换为十进制时精度损失

php - 比较双十进制数

java - 使用 JDBC 将十进制数字插入到 ms-access 时出现问题

c# - 我应该担心这个 DateTime 数学会失去精度吗?

c++ - long double 输出的精度不正确。可能出了什么问题?

c# - xUnit v1 测试出现在 xUnit GUI (xunit.gui.clr4.exe) 但不是 VS 2012 测试资源管理器

c# - Fody/Costura 和 Obfuscar 在 Visual Studio 2017 中的使用

matlab - MATLAB 生成低精度随机数