
本程序实现了斐波那契数列(Fibonacci sequence)
Fibonacci(n int)
函数实现了第n项的斐波那契数列计算,main函数输出了斐波那契数列的前21项,和前21项的前一项和后一项值,在第20项之后,该比值都是0.618034了,所以计算到第21项为就可以说明问题了。
注意,计算比值的时候,要先转换成float32
类型,不然输出的全是0 。
main.go源码如下:
/** *斐波那契数列生成和输出 */ package main import ( "fmt" "strconv" ) //斐波那契数列输出项数 const fn = 21 func main() { sFn := strconv.Itoa(fn) fmt.Println("斐波那契数列前" + sFn + "项:") for i := 1; i <= fn; i++ { fmt.Print(Fibonacci(i)) fmt.Print(" ") } fmt.Println() fmt.Println("相领项比值:") for j := 1; j <= fn; j++ { a := float32(Fibonacci(j)) b := float32(Fibonacci(j + 1)) s := float32(a / b) fmt.Print(s) fmt.Print(" ") } } /** * * @param n int整型 * @return int整型 */ func Fibonacci(n int) int { //f[100]表示最多计算数列前100项,可修改100这人为别的值 var f [100]int f[0] = 0 f[1] = 1 if n > 1 { for i := 2; i < n; i++ { f[i] = f[i-1] + f[i-2] } } return f[n-1] }
在main.go所在目录执行以下命令:
go mod init main go run main.go
输出如下:
斐波那契数列前21项: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 相领项比值: 0 1 0.5 0.6666667 0.6 0.625 0.61538464 0.61904764 0.61764705 0.6181818 0.6179775 0.6180556 0.6180258 0.61803716 0.6180328 0.6180344 0.6180338 0.61803406 0.61803395 0.618034 0.618034
以上程序在go 1.16.3中编译通过
原创文章,作者:AukCode,如若转载,请注明出处:https://www.archeCode.Com/go-fibonacci-sequence-21-output.html