C#函數3遞迴

來源:互聯網
上載者:User

標籤: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遞迴

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.