简体   繁体   English

计算pi的前n位?

[英]Calculate the first n digits of pi?

Hi i am trying to code 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);
        }
    }
}

I am new on C# i need help with set Decimal.Precision pls help.我是 C# 的新手,我需要有关设置 Decimal.Precision 的帮助,请帮忙。

I am trying to calculate n number of pi and write it.我正在尝试计算 n 个 pi 并将其写入。

Code can calculate but i dont know how can write n number of this calculation result.代码可以计算,但我不知道如何写出这个计算结果的n个数。

You can write out the substring of pi from 0 to n:可以写出pi从0到n的substring:

replace: Console.WriteLine(pi);替换: Console.WriteLine(pi);

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

the n + 1 logic increases the number of characters since the decimal "." n + 1 逻辑增加了从小数点“.”开始的字符数。 does not count as a digit.不算作数字。 Notice to increase by 1 only if user specifies more than 1 digit (n > 1).注意仅当用户指定超过 1 个数字(n > 1)时才增加 1。

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

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