在 C# 中使用无穷级数计算 pi
我尝试用 C# 编写以下程序来使用无限递归计算 pi,但我一直对整数/双精度/小数除法感到困惑。
我真的不知道为什么这不起作用,所以请原谅我对强类型的东西缺乏理解,因为我仍在学习 C#。
提前致谢!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static int Main(string[] args)
{
int numeratornext = 2;
int denominatornext = 5;
decimal findto = 100.0M;
decimal pi = 0.0M;
decimal halfpi = 1.0M;
int seriesnum = 1;
int seriesden = 3;
for (int i = 0; i < findto; i++)
{
halfpi += Decimal.Divide((decimal)seriesnum, (decimal)seriesden);
//System.Console.WriteLine(Decimal.Divide((decimal)seriesnum, (decimal)seriesden).ToString());
seriesnum *= numeratornext;
seriesden *= denominatornext;
numeratornext++;
denominatornext += 2;
}
pi = halfpi * 2;
System.Console.WriteLine(pi.ToString());
System.Console.ReadLine();
return 0;
}
}
}
I tried to write the following program in C# to calculate pi using infinite recursion, but I keep getting confused about integer/double/decimal division.
I really have no clue why this isn't working, so pardon me for my lack of understanding of strongly typed stuff, as I'm still learning C#.
Thanks in advance!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static int Main(string[] args)
{
int numeratornext = 2;
int denominatornext = 5;
decimal findto = 100.0M;
decimal pi = 0.0M;
decimal halfpi = 1.0M;
int seriesnum = 1;
int seriesden = 3;
for (int i = 0; i < findto; i++)
{
halfpi += Decimal.Divide((decimal)seriesnum, (decimal)seriesden);
//System.Console.WriteLine(Decimal.Divide((decimal)seriesnum, (decimal)seriesden).ToString());
seriesnum *= numeratornext;
seriesden *= denominatornext;
numeratornext++;
denominatornext += 2;
}
pi = halfpi * 2;
System.Console.WriteLine(pi.ToString());
System.Console.ReadLine();
return 0;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您会感到困惑,因为您使用的是
int
和decimal
,这两者都更适合整数或固定精度的金融计算。我的建议是简单地将所有数值变量声明为double
,这将消除关于返回值类型的任何歧义,因为任何数学运算两个双打会产生另一个双打。(除此之外,您的算法是错误的。但是,您的算法的错误与您正在使用的类型是一个单独的问题。)
Your confusion arises because you're using
int
anddecimal
, both of which are better suited for integers or fixed-precision financial calculations. My suggestion would be to simply declare all of your numeric variables asdouble
here, which will remove any ambiguity about what the types of your return values are, since any mathematical operation on two doubles results in another double.(Aside from this, your algorithm is wrong. However, the wrongness of your algorithm is a separate issue from the types you're using.)