Go 語言遞迴函式

來源:互聯網
上載者:User

標籤:on()   tor   數列   產生   var   class   return   需要   div   

Go 語言遞迴函式

遞迴,就是在啟動並執行過程中調用自己。

文法格式如下:

1 func recursion() {2    recursion() /* 函數調用自身 */3 }4 5 func main() {6    recursion()7 }

Go 語言支援遞迴。但我們在使用遞迴時,開發人員需要設定允出準則,否則遞迴將陷入無限迴圈中。

遞迴函式對於解決數學上的問題是非常有用的,就像計算階乘,產生斐波那契數列等。

----------------------------------------------------------------------------------------------

階乘

以下執行個體通過 Go 語言的遞迴函式執行個體階乘:

 1 package main 2  3 import "fmt" 4  5 func Factorial(x int) (result int) { 6   if x == 0 { 7     result = 1;     8   } else { 9     result = x * Factorial(x - 1);10   }11   return;12 }13 14 func main() {  15     var i int = 1516     fmt.Printf("%d 的階乘是 %d\n", i, Factorial(i))17 }

以上執行個體執行輸出結果為:

15 的階乘是 1307674368000
斐波那契數列

以下執行個體通過 Go 語言的遞迴函式實現斐波那契數列:

 1 package main 2  3 import "fmt" 4  5 func fibonacci(n int) int { 6   if n < 2 { 7    return n 8   } 9   return fibonacci(n-2) + fibonacci(n-1)10 }11 12 func main() {13     var i int14     for i = 0; i < 10; i++ {15        fmt.Printf("%d\t", fibonacci(i))16     }17 }

以上執行個體執行輸出結果為:

0    1    1    2    3    5    8    13    21    34

 

Go 語言遞迴函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.