需要帮助理解 Eloquent Javascript 中的递归函数示例 [英] Need help understanding recursive function example from Eloquent Javascript

查看:32
本文介绍了需要帮助理解 Eloquent Javascript 中的递归函数示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function power(base, exponent) {
  if (exponent == 0)
  return 1;
else
  return base * power(base, exponent - 1);
}

我认为我理解递归的基本原理,它只是意味着您在函数本身内部调用函数.这可用于执行各种循环,但我无法弄清楚上面的代码实际上如何决定循环以找出数字的指数值.我使用函数 power(2,5) 作为我的参数,函数知道答案是 32,但是如何呢?函数循环本身是否每次从指数中减去 1,然后乘以 base * base 直到指数达到零?如果是这样的话,在函数中调用 power 函数是如何准确实现这一点的呢?一旦指数达到零,函数不会只返回 1 而不是正确答案吗?

I think that I understand the basic principle of recursion, it simply means you are calling the function within the function itself. This can be used to perform a loop of sorts, but what I cant figure out is how the above code actually decides to loop in order to figure out the exponential value of a number. I used function power(2,5) as my argument and the function knew the answer was 32, but how? Does the function loop itself subtracting 1 from the exponent each time, and multiplying base * base until exponent reaches zero? And if thats the case, how does calling the power function within the function accomplish this exactly? And once exponent reaches zero, wouldnt the function then just return 1 and not the correct answer?

推荐答案

我认为每个递归步骤(调用自身的函数)都会产生一个更短、更容易的问题.

I consider each recursive step (the function calling itself) producing a shorter and easier problem.

最简单的问题是 power(base, 0),它满足 exponent == 0 并返回 1(任何底数的零次方都是 1).

The easiest problem is power(base, 0), which satisfies exponent == 0 and returns one (any base to the zeroth power is 1).

然后,请注意,无论指数有多大,它都会将 exponent 减一,以保证最终会达到指数为零的最简单"问题.它只能是负数,否则永远不会达到这个基本情况".

Then, notice that no matter how large exponent is, it is reducing exponent by one, guaranteeing that it will eventually reach the "easiest" problem where the exponent is zero. It only can't be negative, or else this "base case" is never reached.

因此,2^5 或 power(2, 5) 变为 2 * 2^4.2^4 = 2 * 2^3.通过继续这个扩展,我们得到 2 * 2 * 2 * 2 * 2 * 1,等于 32.1 表示情况 exponent == 0 为真.

So, 2^5, or power(2, 5), becomes 2 * 2^4. And 2^4 = 2 * 2^3. By continuing this expansion, we get 2 * 2 * 2 * 2 * 2 * 1, which equals 32. The 1 represents the case exponent == 0 being true.

计算必须跟踪它累积了多少次乘法,并且一旦达到 exponent == 0 的基本情况,将所有数字相乘.它无法预先确定power(base, exponent-1) 将返回什么.

The computation has to keep track how many of these multiplications it has accumulated, and once the base case of exponent == 0 is reached, multiply all numbers together. It cannot know in advance with certainty what power(base, exponent-1) will return.

这篇关于需要帮助理解 Eloquent Javascript 中的递归函数示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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