方式1:
func test(n1 int){
if(n1 > 2){
n1--
test(n1)
}
fmt.Println("n1 = ",n1)
}
func main(){
test(5)
}
结果:
n1 = 2
n1 = 2
n1 = 3
n1 = 4
运行原理:
方式2:
//递归 方式2
func test2(n1 int){
if(n1 > 2){
n1--
test2(n1)
} else {
fmt.Println("n1 = ",n1)
}
}
func main(){
test2(5)
}
结果
n1 = 2
运行原理:
在条件不满足时 执行else 时才会打印输出 不满足时会一直调用本身 所以结果 n1 = 2
斐波那契数
如 1 1 2 3 5 8 13 21 34 (当前数是前俩个数的和 1 1 除外)
随机一个整数 求出 斐波那契数 是多少
func fbn(n int) int {
if( n == 1 || n == 2){
return 1
}else{
return fbn( n - 1 ) + fbn ( n - 2 )
}
}
func main(){
fmt.Println(fbn(10))
}