Fibonacci numbers : 1,1,2,3,5,8,13,21 ...
the law :
- When n == 1 || n == 2, returns 1
- When n> = 2, and return to the previous f (n-1) + f (n-2) of two numbers
code show as below:
package main
import "fmt"
func fbn(n int) int {
if (n == 1 || n == 2) {
return 1
} else {
return fbn(n-1)+ fbn(n-2)
}
}
func main() {
fmt.Println("您想输出第几个数的斐波那契数:")
var x int
fmt.Scan(&x)
res :=fbn(x)
fmt.Printf("第%v个数的斐波那契数是%v",x,res)
}
Execution results as shown below: