转到—声明的且未使用的错误,当我认为已对变量执行此操作时

此代码有什么问题?


package main


import "fmt"


// fibonacci is a function that returns

// a function that returns an int.

func fibonacci() func() int {

    prev := 0

    curr := 1

    return func() int {

        temp := curr

        curr := curr + prev

        prev := temp

        return curr

    }

}


func main() {

    f := fibonacci()

    for i := 0; i < 10; i++ {

        fmt.Println(f())

    }

}

prog.go:13:已声明且未使用prev


FFIVE
浏览 173回答 2
2回答

慕少森

如果您进行了Kevin Ballard建议的更改,那么,package mainimport "fmt"// fibonacci is a function that returns// a function that returns an int.func fibonacci() func() int {&nbsp; &nbsp; prev := 0&nbsp; &nbsp; curr := 1&nbsp; &nbsp; return func() int {&nbsp; &nbsp; &nbsp; &nbsp; temp := curr&nbsp; &nbsp; &nbsp; &nbsp; curr = curr + prev&nbsp; &nbsp; &nbsp; &nbsp; prev = temp&nbsp; &nbsp; &nbsp; &nbsp; return curr&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; f := fibonacci()&nbsp; &nbsp; for i := 0; i < 10; i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(f())&nbsp; &nbsp; }}输出:123581321345589输出不是斐波那契数列。对于斐波那契数列,package mainimport "fmt"func fibonacci() func() int {&nbsp; &nbsp; a, b := 0, 1&nbsp; &nbsp; return func() (f int) {&nbsp; &nbsp; &nbsp; &nbsp; f, a, b = a, b, a+b&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; f := fibonacci()&nbsp; &nbsp; for i := 0; i < 10; i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(f())&nbsp; &nbsp; }}输出:0112358132134
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go