douqi1212 2018-05-30 15:53
浏览 8
已采纳

说明:函数返回相同的函数

func main() {
    go spinner(100 * time.Millisecond)
    const n = 45
    fibN := fib(n) // slow
    fmt.Printf("Fibonacci(%d) = %d
", n, fibN)
}

func spinner(delay time.Duration) {
    for {
        for _, r := range `-\|/` {
            fmt.Printf("%c", r)
            time.Sleep(delay)
        }
    }
}

func fib(x int) int {
    if x < 2 {
        return x
    }
    return fib(x-1) + fib(x-2)
}

can you explain above fib function ,how the results are obtained.

fib function return a fib calls ,how does the end results come?

  • 写回答

1条回答 默认 最新

  • douwei1904 2018-05-30 16:09
    关注

    The key is in this function:

    func fib(x int) int {
        if x < 2 {
            return x
        }
        return fib(x-1) + fib(x-2)
    }
    

    If x<2 the function returns immediately, if not it retrieves the result from a call to fib with a smaller value of x

    For recursive calls there are the 3 Laws of Recursion:

    1. A recursive algorithm must have a base case.
    2. A recursive algorithm must change its state and move toward the base case.
    3. A recursive algorithm must call itself, recursively.

    http://interactivepython.org/courselib/static/pythonds/Recursion/TheThreeLawsofRecursion.html

    In your example, the base case is when x < 2. The state change is the reduction by 1 or 2 and your function calls itself recursively so the three laws are met.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?