以下代码用于课堂作业问题。该程序的目标是使用模拟飞镖投掷在正方形内的一个圆上来估计Pi的值。想法是使用2个随机数来计算飞镖是否击中了圆圈。如果(x-0.5)^ 2 +(y-0.5)^ 2 <0.25,则飞镖落在圆内。 (“命中数” /未命中数)* 4是Pi的近似值。投掷的飞镖越多,估计就越接近。以下代码生成随机数,似乎在计算“ throwLocation”,但始终输出估计值0。我相信这可能是因为hits变量未正确递增。由于总点击数= 0,因此估计值将为0,因为0 /投掷次数始终为零。这段代码中的方法有问题吗?还是还有其他问题?谢谢
namespace hw_6_17
{
class PiWithDarts
{
public int throwDarts;
public int hits = 0;
public double piEst;
//increments the number of thrown darts
public void DartThrown()
{
throwDarts++;
}
//calculates and tracks hits
public void Hits()
{
double xValue;
double yValue;
double throwLocation;
Random r = new Random();
xValue = r.NextDouble();
yValue = r.NextDouble();
Console.WriteLine("{0}", xValue);
Console.WriteLine("{0}", yValue);
throwLocation = ((xValue - 0.5) * (xValue - 0.5)) + ((yValue - 0.5) * (yValue - 0.5));
Console.WriteLine("throw, {0}", throwLocation);
if (throwLocation < .25)
{
hits++;
}
}
//estimate pi based on number of hits
public void CalcPi()
{
piEst = (hits / throwDarts) * 4;
Console.WriteLine("Based off the darts thrown, Pi is approximately {0}.", piEst);
Console.ReadLine();
}
static void Main(string[] args)
{
int numToThrow;
int count = 0;
PiWithDarts NewRound = new PiWithDarts();
Console.WriteLine("How many darts will be thrown?");
numToThrow = int.Parse(Console.ReadLine());
while(count < numToThrow)
{
NewRound.DartThrown();
NewRound.Hits();
count++;
}
NewRound.CalcPi();
}
}
}
答案 0 :(得分:2)
问题是throwDarts
和hits
的类型为int
您需要将这些int
变量强制转换为double
或float
才能正确获得结果
您可以使用此
public void CalcPi()
{
piEst = ((double)hits / (double)throwDarts) * 4;
Console.WriteLine("Based off the darts thrown, Pi is approximately {0}.", piEst);
Console.ReadLine();
}