C#中方法的变量

问题描述 投票:0回答:1

以下代码用于课堂作业问题。该计划的目标是使用模拟飞镖投掷在正方形内的圆圈估计Pi的值。这个想法是使用2个随机数来计算飞镖是否在圆圈内击中。如果(x-0.5)^ 2 +(y-0.5)^ 2 <0.25,则镖落在圆内。 (“命中数”/未命中数)* 4是Pi的近似值。投掷的飞镖越多,估计越接近。下面的代码生成随机数并且似乎计算“throwLocation”,但它总是输出0的估计值。我相信这可能是因为命中变量没有正确递增。由于命中总是= 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();
    }
}
}
c# class random methods montecarlo
1个回答
2
投票

问题是throwDartshitsint类型 你需要将这些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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.