[英]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.