递归函数 [英] Recursive Function

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

问题描述

由于以下递归函数:

  // pre-条件:y为非负。
神秘INT(INT X,int y)对{
    如果(Y == 0)返回X;
    返回2 *神秘(X,Y-1);
}

什么是神秘的返回值(3,2)?

下面是我的调用堆栈:

 返回2 *神秘(3,2-1)=> 2 * 3 => 6,2 * 1 =>神秘的(6,2)
返回2 *神秘(6,2-1)=> 6 * 2 => 12,2 * 2 =>神秘(12,2)

但好像Ÿ将永远不会达到0。我在做什么错了?


解决方案


神秘的(3,2)= 2 *神秘(3,1)
= 2 * 2 *神秘(3,0)
= 2 * 2 * 3
= 12

Given the following recursive function:

// Pre-condition: y is non-negative.
int mysterious(int x, int y) {
    if (y == 0) return x;
    return 2*mysterious(x, y-1);
}

What is the return value of mysterious(3, 2)?

Here is my call stack:

return 2*mysterious(3, 2-1) => 2*3 => 6, 2*1 => mysterious(6,2)
return 2*mysterious(6, 2-1) => 6*2 => 12, 2*2 => mysterious(12, 2)

But it seems like y will never reach 0. What am I doing wrong?

解决方案

mysterious(3, 2)

= 2 * mysterious(3, 1)
= 2 * 2 * mysterious(3, 0)
= 2 * 2 * 3
= 12

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

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