close

費氏數列 依據維基所說的,印出的結果如下
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233……

    protected void Page_Load(object sender, EventArgs e)
    {
        int Num = 10;
        int p1 = 1; // 第一個數 
        int p2 = 1; // 第二個數 
        int res = 0; ;
        Label1.Text = "";
        Label1.Text += string.Format("{0}-{1}", p1, p2); // 印出第一個和第二個數

        for (int i = 3; i <= Num; i++)
        {
            res = p1 + p2;
            p1 = p2;
            p2 = res;
            Label1.Text += (Label1.Text == "" ? "" : "-") + string.Format("{0}", res);
        }
    }

若需要 for 迴圈的程式,請看另一篇 [C#] 費氏數列(Fibonacci) 遞迴


arrow
arrow

    Roger 發表在 痞客邦 留言(0) 人氣()