写点什么

Go- 递归函数

用户头像
HelloBug
关注
发布于: 4 小时前
Go- 递归函数

Go 学习笔记,学习内容《Go入门指南》


主要介绍以下内容:

  • 递归函数举例

  • 函数之间闭环调用


代码示例可以直接运行

package main
import ( "fmt")
func main() { /* 递归函数:在函数内部调用函数本身 递归调用可能会出现栈溢出,使用懒惰求值的方式解决,go中使用管道和协程解决 */ res := 0 for i := 0; i < 5; i++ { res = fibonacci(i) fmt.Printf("fibonacci(%d) is %d\n", i, res) } /* 输出: fibonacci(0) is 1 fibonacci(1) is 1 fibonacci(2) is 2 fibonacci(3) is 3 fibonacci(4) is 5 */
/* 计算阶乘 */ res = factorial(30) fmt.Printf("factorial(30) is %d\n", res) // 输出:factorial(30) is -8764578968847253504---结果溢出
res = factorial(12) fmt.Printf("factorial(12) is %d\n", res) // 输出:factorial(12) is 479001600
/* 函数之间相互调用形成闭环 */ fmt.Printf("%2d is odd is %t\n", 16, odd(16)) // 输出:16 is odd is true fmt.Printf("%2d is odd is %t\n", 15, odd(15)) // 输出:15 is odd is false fmt.Printf("%2d is odd is %t\n", 0, odd(0)) // 输出: 0 is odd is true fmt.Printf("%2d is even is %t\n", 16, even(16)) // 输出:16 is even is false fmt.Printf("%2d is even is %t\n", 15, even(15)) // 输出:15 is even is true fmt.Printf("%2d is even is %t\n", 0, even(0)) // 输出: 0 is even is false
}
func fibonacci(n int) (res int) { if n <= 1 { return 1 }
res = fibonacci(n-1) + fibonacci(n-2) return}
func RevSig(nr int) int { if nr < 0 { return -nr }
return nr}
func odd(nr int) bool { if nr == 0 { return true }
return even(RevSig(nr) - 1)}
func even(nr int) bool { if nr == 0 { return false } return odd(RevSig(nr) - 1)}
func factorial(n int) int { if n <= 1 { return 1 }
return n * factorial(n-1)}
复制代码


发布于: 4 小时前阅读数: 1
用户头像

HelloBug

关注

还未添加个人签名 2018.09.20 加入

还未添加个人简介

评论

发布
暂无评论
Go- 递归函数