Pergunta

Com registro para esta questão Pi em C #

Codifiquei o código abaixo e forneceu uma saída com os últimos 6 dígitos como 0. Portanto, quero melhorar o programa convertendo tudo para decimal.Nunca usei decimal em C # em vez de um duplo antes e só me sinto confortável com o duplo em meu uso regular.

Então, por favor, ajude-me com a conversão decimal, tentei substituir todos os duplos em decimal no início e não deu certo :(.

 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);
    }
    }
}

Saída

Obtenha PI dos métodos mostrados aqui 3.14159265358979000000 Obter PI da constante de classe .NET Math 3,14159265358979000000

Foi útil?

Solução

Bem, substituir double por decimal é um bom começo - e então tudo que você precisa fazer é alterar a constante de 2.0 para 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);
    }
}

É claro que ainda terá uma precisão limitada, mas um pouco mais do que double.O resultado é 3.14159265358979325010.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top