標籤:gen space write fun col collect 使用 遞迴 ext
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
// 要理解遞迴,先要理解遞迴. (這隻是一句玩笑話 )
// 遞迴,顧名思義就是遞來歸去,如此反覆,直到不符合某個條件. 而函數遞迴意思也就是函數調用函數自己. 下面用代碼來樣本:
static int Funtion(int n) // 用這個函數實現階乘 , n表示階乘的次數
{
if (n <= 1)
return 1;
else
return n * Funtion(n - 1);
}
// 再使用一個函數來表示費伯納西數列 (費伯納西數列的規律是, 從第三項開始,每一項都是前兩項之和)
static int Fei(int n) // n 表示費伯納西數列的項.
{
if (n < 3)
return 1;
else
return Fei(n - 1) + Fei(n - 2);
}
static void Main(string[] args)
{
// 調用上面的階乘函數.
Console.WriteLine("請輸入需要階乘的次數:");
Console.WriteLine(Funtion(Convert.ToInt32 (Console.ReadLine())));
//調用費伯納西數列函數.
Console.WriteLine("請輸入你想要實現多少項");
int n = Convert.ToInt32(Console.ReadLine());
// 用 for 語句把每一項都列印出來.
for (int i = 1; i <= n; i++)
{
Console.Write("{0}\t", Fei(i));
if (i % 5 == 0)
Console.WriteLine();
}
}
}
}
/* 運行結果如下 :
請輸入需要階乘的次數:
10
3628800
------------------------
請輸入你想要實現多少項
30
1 1 2 3 5
8 13 21 34 55
89 144 233 377 610
987 1597 2584 4181 6765
10946 17711 28657 46368 75025
121393 196418 317811 514229 832040
*/
C#函數3遞迴