需要帮助理解C ++中的递归函数 [英] Need help with understanding a recursive function in C++

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

问题描述

我试图理解c ++中的一个函数。

据我所知,在这里a = x

和x = 19之后的x值%4 + 2是5,所以else块将被执行

这段代码的输出是24.

我想知道,怎么样?谁能请解释我。

谢谢。

代码如下。



我尝试过:



I am trying to understand a function in c++.
as far as i understand it that in here a=x
and the value of x after x=19%4+2 is 5, so the else block will be executed
And the output of this code is 24.
I want to know, How? Could anyone please explain me.
Thanks.
The code is below.

What I have tried:

#include<iostream>

using namespace std;


int fun1(int a );

int main(){
int x=19;
x= 19%4+2;
cout<<fun1(x);

}

int fun1(int a){
	if(a==1 || a==2){
		return 2*a;
	}else {
		return 2+fun1(a-1)+fun1(a-2);
	}
}

推荐答案

我会使用调试器逐步执行代码并检查变量。 fun1 被调用9次,所以这是非常可行的。



首次通话,a = 5:
I would use the debugger to step through the code and check the variables. fun1 is called 9 times, so that's quite doable.

First call, a = 5:
if(a==1 || a==2){ // False, a = 5
    return 2*a;
}else { // True
    return 2+fun1(a-1)+fun1(a-2); // Call fun1() with values 5 - 1 = 4, and with 5 - 2 = 3
}

第二次调用,a = 4:

Second call, a = 4:

if(a==1 || a==2){ // False, a = 4
    return 2*a;
}else {              // True
    return 2+fun1(a-1)+fun1(a-2); // Call fun1() with values 4 - 1 = 3, and with 4 - 2 = 2
}

第三次调用,a = 3:

Third call, a = 3:

if(a==1 || a==2){ // False, a = 3
    return 2*a;
}else { // True
    return 2+fun1(a-1)+fun1(a-2); // Call fun1() with values 3 - 1 = 2, and with 3 - 2 = 1
}

第四次调用,a = 2:

Fourth call, a = 2:

if(a==1 || a==2){ // True
    return 2*a; // Return 2 * 2 = 4
}else {
    return 2+fun1(a-1)+fun1(a-2);
}



等。


etc.


还要看看:C++递归 - 递归函数 [ ^ ]。


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

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