[英]How to get decimal to n places precision in C# program for Pi
注册到C#中的Pi#
我编写了下面的代码并给出了最后6位数为0的输出。所以我想通过将所有内容转换为十进制来改进程序。 我从来没有在C#中使用过十进制而不是之前的双倍,而我在常规使用中只能使用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);
}
}
}
产量
从此处显示的方法获取PI 3.14159265358979000000从.NET Math类常量获取PI 3.14159265358979000000
好吧,用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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.