在这个例子中无法理解递归是如何工作的 [英] Can't understand how recursion works in this example

查看:90
本文介绍了在这个例子中无法理解递归是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我获得了以下代码:

public int func(int n){
  if(n == 1)
     return 2;
  else 
     return 3 * func(n-1)+1;
}

我可以理解像factorial和fibonacci这样的递归,但对于这个我倾斜。
我试图跟踪逻辑:

I can understand recursion in things like factorial and fibonacci, but for this one I cant. I tried to trace the logic:

if n is 3:
return 3 * func(2) + 1
return 3 * func(1) + 1
return 3 * 2 + 1
return 7

我总是以7与任何其他数字结束,我知道这是错误的,因为我在运行程序时会得到不同的值。你能帮我理解递归是如何工作的吗?

I always end up with 7 with any other number and I know this is wrong because I get different values when I run the program. Can you help me understand how recursion works here?

推荐答案

我认为这是不言自明的,如果你需要更多的信息只需评论!

I think this is self-explanatory, if you need more informations just comment !

if n is 3:
return 3 * func(2) + 1
return 3 * (3 * func(1) + 1) + 1 //func(2) is equals to 3 * func(1) + 1
return 3 * (3 * 2 + 1) + 1 //func(1) is equals to 2
return 22

这篇关于在这个例子中无法理解递归是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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