遞迴的經典範例,費波那契數列.
// hello29
package main
import (
"fmt"
)
func main() {
result := 0
for i := 0; i <= 15; i++ {
result = fibonacci(i)
fmt.Printf("fibonacci(%2d) -> %3d\n", i, result)
}
}
func fibonacci(n int) (rtn int) {
if n <= 1 {
rtn = 1
} else {
rtn = fibonacci(n-1) + fibonacci(n-2)
}
return
}
執行結果:
$ ./hello29
fibonacci( 0) -> 1
fibonacci( 1) -> 1
fibonacci( 2) -> 2
fibonacci( 3) -> 3
fibonacci( 4) -> 5
fibonacci( 5) -> 8
fibonacci( 6) -> 13
fibonacci( 7) -> 21
fibonacci( 8) -> 34
fibonacci( 9) -> 55
fibonacci(10) -> 89
fibonacci(11) -> 144
fibonacci(12) -> 233
fibonacci(13) -> 377
fibonacci(14) -> 610
fibonacci(15) -> 987
hitomitanaka提到:
費波那契數列
不知道這個數列是什麼的邦友,請自動出列....
小雨大會親自授課~~~~