Pregunta

Con reg a esta pregunta Pi en C #

Codifiqué el siguiente código y me dio una salida con los últimos 6 dígitos como 0. Así que quiero mejorar el programa convirtiendo todo a decimal.Nunca he usado decimal en C # en lugar de un doble antes y solo me siento cómodo con el doble en mi uso habitual.

Así que, por favor, ayúdame con la conversión decimal, intenté reemplazar todo el doble por decimal al principio y no salió bien :(.

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

Salida

Obtenga PI de los métodos que se muestran aquí 3.14159265358979000000 Obtener PI de la constante de clase .NET Math 3.14159265358979000000

¿Fue útil?

Solución

Bueno, reemplazar double con decimal es un buen comienzo, y luego todo lo que necesita hacer es cambiar la constante de 2.0 a 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);
    }
}

Por supuesto, todavía tendrá una precisión limitada, pero un poco más que double.El resultado es 3.14159265358979325010.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top