我的Monte Carlo Pi程序无法正确计算。基本上,pi仅在此刻仅显示最多2个小数点,并且我认为计算出了问题,因为随着数值的增加,最近的pi计算为2.98-3.04。
我的代码粘贴在下面。
static void Main(string[] args)
{
double n;
double count;
double c = 0.0;
double x = 0.0, y = 0.0;
double pi;
string input;
Console.WriteLine("Please input a number of dots for Monte Carlo to calculate pi.");
input = Console.ReadLine();
n = double.Parse(input);
Random rand = new Random();
for (int i = 1; i < n; i++ )
{
x = rand.Next(-1, 1);
y = rand.Next(-1, 1);
if (((x * x) + (y * y) <= 1))
c++;
pi = 4.0 * ( c / i );
Console.WriteLine("pi: {0,-10:0.00} Dots in square: {1,-15:0} Dots in circle: {2,-20:0}", pi, i, c);
}
}
这些电话
x = rand.Next(-1, 1);
y = rand.Next(-1, 1);
给你一个整数。但是您需要doubles
:
x = rand.NextDouble() * 2 - 1;
y = rand.NextDouble() * 2 - 1;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句