一、什么是递归函数?
当一个函数在其函数体内调用自身,则称之为递归。
二、引用经典例子:斐波那切数列
package main import "fmt" func main(){ result := 0 for i := 0; i <= 10; i++ { result = fibonacci(i) fmt.Printf("fibonacci(%d) is: %d ", i, result) } } func fibonacci(n int )(res int){ if n <= 1{ res = 1 }else { res = fibonacci(n-1) + fibonacci(n-2) } return }
//输出:
fibonacci(0) is: 1
fibonacci(1) is: 1
fibonacci(2) is: 2
fibonacci(3) is: 3
fibonacci(4) is: 5
fibonacci(5) is: 8
fibonacci(6) is: 13
fibonacci(7) is: 21
fibonacci(8) is: 34
fibonacci(9) is: 55
fibonacci(10) is: 89
调用前两个数,相加,得到值。
三、相互闭环调用
package main import "fmt" func main() { fmt.Printf("%d is event: is %t ", 16, even(16)) fmt.Printf("%d is odd: is %t ", 17, odd(17)) fmt.Printf("%d is odd: is %t ", 18, odd(18)) } func even(nr int) bool { if nr == 0 { return true } return odd(RevSign(nr) - 1) } func odd(nr int) bool { if nr == 0 { return false } return even(RevSign(nr) - 1) } func RevSign(nr int) int { if nr < 0 { return -nr } return nr }
输出:
16 is event: is true
17 is odd: is true
18 is odd: is false