递归是如何返回的? [英] How does recursion work its way back?

查看:41
本文介绍了递归是如何返回的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力更深入地了解递归,但我正在努力解决为什么它会以这种方式工作.我知道这个函数返回前一个返回值的平方(2、4、16、256 等),但我想知道它是如何得到答案的.

I'm working to understand recursion more in depth and I'm struggling with WHY it works the way it does. I know that this function returns the square of the previous return (2, 4, 16, 256, etc.), but I'm wonder how it gets the answer.

我对递归的理解是它会迭代回基本情况,但这让我相信它最终总是会返回基本情况.它是如何恢复到每次返回新东西的?

My understanding of recursion is that it iterates back down to the base case, but that leads me to believe that it would eventually always return the base case. How does it work its way back up to returning something new every time?

int p1a(int num) {
   if (num == 1) { return 2; }
   else {
      return pow(p1a(num-1), 2); 
   }
}

这是我的想法的一个例子

Here's an example of my thinking

num = 3
passes through the base case and hits pow(p1a(num-1), 2)
moves back to the start
again passes through the base case and hits pow(p1a(num-1), 2)
at this point, num = 1, so it would return 2

它是如何返回 16 的?我了解该函数返回的内容,但我仍停留在到达那里的过程中.

How is it working its way back up to return 16? I understand what the function returns, but I'm stuck on the process of getting there.

推荐答案

您正在线性地考虑步骤,而执行实际上是嵌套的(以缩进表示):

You're thinking about the steps linearly, while the execution is actually nested (represented by indenting):

call p1a(3)
    call p1a(2)
        call p1a(1)
            return 2
        return pow(2, 2)
    return pow(4, 2)

所以最后的 return 返回值 16.

So the final return returns the value 16.

这篇关于递归是如何返回的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆