繁体   English   中英

计算pi的前n位?

[英]Calculate the first n digits of pi?

嗨,我正在尝试编写代码计算 pi 的前 n 位数字

using System;
using System.Numerics;
namespace PiCalculator
{
    
    class Program
    {
        
        static void Main(string[] args)
        {
            System.Decimal.Precision = 5;
            Console.WriteLine("How Many Digit?");
            int n = Convert.ToInt32(Console.ReadLine());

            decimal pi = 0;
            decimal t = 0;
            decimal deno = 0;
            int k = 0;

            t=1*(Factorial(1))*(13591409+545140134*k);
            deno = ((decimal)Factorial(3*k))*((decimal)Math.Pow((double)Factorial(k),3))*((decimal)(Math.Pow(640320,(3*k))));
            pi += t/deno;
            pi = pi * 12 / (decimal)Math.Pow(640320,1.5);
            pi = 1/pi;

            Console.WriteLine(pi);
        }

        // Factorial fonksiyonu
        static decimal Factorial(int n)
        {
            if (n == 0)
                return 1;

            return n * Factorial(n - 1);
        }
    }
}

我是 C# 的新手,我需要有关设置 Decimal.Precision 的帮助,请帮忙。

我正在尝试计算 n 个 pi 并将其写入。

代码可以计算,但我不知道如何写出这个计算结果的n个数。

可以写出pi从0到n的substring:

替换: Console.WriteLine(pi);

使用: Console.WriteLine(pi.ToString().Substring(0, (n > 1)? n + 1: n));

n + 1 逻辑增加了从小数点“.”开始的字符数。 不算作数字。 注意仅当用户指定超过 1 个数字(n > 1)时才增加 1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM