如何在Pi的C#程序中将小数转换为n位精度 [英] How to get decimal to n places precision in C# program for Pi

查看:111
本文介绍了如何在Pi的C#程序中将小数转换为n位精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此问题有规矩 Pi in C#

我对下面的代码进行了编码,并给出了最后6位数字为0的输出.因此,我想通过将所有内容都转换为十进制来改进程序.我从来没有在C#中使用小数而不是以前的double,我只对常规使用double感到满意.

I coded the below code and gives a output with last 6 digits as 0. So I want to improve the program by converting everything to decimal. I have never used decimal in C# instead of a double before and I am only comfortable with double in my regular use.

所以请帮助我进行十进制转换,我尝试在开始时将所有的double替换为十进制,但效果不好:(.

So please help me with decimal conversion, i tried to replace all double to decimal at start and it didnt turn good :(.

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

输出

从此处显示的方法获取PI 3.14159265358979000000从.NET Math类常量获取PI 3.14159265358979000000

Get PI from methods shown here 3.14159265358979000000 Get PI from the .NET Math class constant 3.14159265358979000000

推荐答案

好吧,用decimal替换double是一个很好的开始-然后您要做的就是将常数从2.0更改为2.0m:

Well, replacing double with decimal is a good start - and then all you need to do is change the constant from 2.0 to 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);
    }
}

当然,它的精度仍然有限​​,但比double略高.结果为3.14159265358979325010.

Of course it's still going to have limited precision, but slightly more than double. The result is 3.14159265358979325010.

这篇关于如何在Pi的C#程序中将小数转换为n位精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆