42 lines
1.3 KiB
C#
42 lines
1.3 KiB
C#
|
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.Linq;
|
|||
|
using System.Text;
|
|||
|
using System.Threading.Tasks;
|
|||
|
|
|||
|
namespace ConsoleApplication2
|
|||
|
{
|
|||
|
class Program
|
|||
|
{
|
|||
|
static void Main(string[] args)
|
|||
|
{
|
|||
|
while (true)
|
|||
|
{
|
|||
|
//π/4 = 1 -1/3 +1/5 -1/7 +1/9 -1/11 +……,精确至少4位小数.
|
|||
|
Console.WriteLine("请输入运算次数进行下一次计算...");
|
|||
|
decimal a = decimal.Parse(Console.ReadLine());
|
|||
|
Console.WriteLine("输入的次数: {0}", a);
|
|||
|
decimal result = 0;
|
|||
|
bool add = true;
|
|||
|
for (decimal i = 1; i < a; i += 2)
|
|||
|
{
|
|||
|
//result += 1d / (2d * i - 1d) * Math.Pow(-1d, i - 1d);
|
|||
|
if (add)
|
|||
|
{
|
|||
|
result += 1m / i;
|
|||
|
add = false;
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
result -= 1m / i;
|
|||
|
add = true;
|
|||
|
}
|
|||
|
//Console.WriteLine(result * 4d);
|
|||
|
}
|
|||
|
Console.WriteLine("PI的结果为: {0}", (result * 4m));
|
|||
|
Console.WriteLine("PI的结果为: {0}", (result * 4m).ToString("#0.0000"));
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|