dongyun4010 2016-07-09 14:00
浏览 87
已采纳

算法:了解递归函数

I'm learning Golang and i'm trying to understand the logic behind the output of a recursive function.

Here is my program :

package main 

import(
    "fmt"
)

func rec(i int) (int){
    if i == 5{
        fmt.Println("Break", i)
        return i
    }

    rec(i+1)
    fmt.Println("i = ", i)

    return i
}

func main(){
    j := 0
    j = rec(1)

    fmt.Println("Value j = ", j)

}

The output:

Break 5
i =  4
i =  3
i =  2
i =  1
Value j =  1

My questions are:

Why the first output (break 5) is in the top of outputs? Isn't the last output in my function to be printed ?

And why in the main function

j = rec(1) 

return 1 and ignore the return of the condition ?

if i == 5{ 
        fmt.Println("Break", i)
        return i // Here normally the return will be: return 5 ??
    }

PS: I'm using Go version go1.2.1 linux/386 under Ubuntu 14.04

Thanks for your answers.

  • 写回答

1条回答 默认 最新

  • douzhajie7168 2016-07-09 14:08
    关注

    This line in the func rec(i int) function

    rec(i+1) // recurse at the i+1 value
    fmt.Println("i = ", i)
    

    Recursively iterates i until it reaches 5, after which your if condition triggers, which is why 5 is first printed, and then it successively goes down through the call stack, printing 4, then 3, ... etc.

    This is a question r.e. recursion, not Go specifically. There are numerous resources to help you understand, here is an explanation of recursion in the Towers of Hanoi problem.

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

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划