GoLang练习实例100之006----斐波那契数列

不折腾难受斯基 ·
package main import ( "fmt" ) func fib(n int) (res []int) { res = make([]int, 0) if n < 0 { return } res = append(res, 0) if n == 1 { return } res = append(res, 1) for i := 2; i <= n; i++ { res = append(res, res[i-2]+res[i-1]) } return } func main() { var n int = 10 res := fib(n) fmt.Println(res) }
#3
更多评论
效率不高,建议直接返回slice,后面的元素利用前面的计算结果..
#1
package main import ( "fmt" ) func fib(n int) (res []int) { res = make([]int, 0) res = append(res, 0) res = append(res, 1) for i := 2; i <= n; i++ { res = append(res, res[i-2]+res[i-1]) } return } func main() { var n int = 10 res := fib(n) fmt.Println(res) }
#2