簡體   English   中英

C#中方法中的變量

[英]Variables in methods in C#

以下代碼用於課堂作業問題。 該程序的目標是使用模擬飛鏢投擲在正方形內的一個圓上來估計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();
    }
}
}

問題是throwDartshitsint類型
您需要將這些int變量float轉換為doublefloat以正確獲得結果
你可以用這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM