C# 方法中的变量

Variables in methods in C#

下面的代码是针对一道class作业题。该程序的目标是使用模拟飞镖在正方形内的圆圈内投掷来估计 Pi 的值。这个想法是使用 2 个随机数来计算飞镖是否击中圆圈内。如果 (x - 0.5)^2 + (y - 0.5)^2 < 0.25 飞镖落在圆圈内。 ("hits" 的数量 / 未命中的数量) * 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();
    }
}
}

问题是 throwDartshits 的类型是 int
您需要将这些 int 变量转换为 doublefloat 才能正确获得结果
你可以使用这个

public void CalcPi()
    {
        piEst = ((double)hits / (double)throwDarts) * 4;
        Console.WriteLine("Based off the darts thrown, Pi is approximately {0}.", piEst);
        Console.ReadLine();
    }