对于这个问题 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/