注册 登录
编程论坛 C++教室

具体是怎么来递归调用的呢?想了好久!有人能指点一下吗?感谢感谢!

花栖醉露 发布于 2018-11-29 16:43, 1525 次点击
#include <iostream>
using namespace std;
int c (int x, int y){
    if(x<1) return y+2;
    else if(x % 2 == 1) return (y*c(x-1,y+1));
    else return (c(x/2,y)*3);
}
int  main()
{
    cout<<c(6,2)<<endl;
    return 0;
}
运行结果是324,怎么得到的呢?
3 回复
#2
花栖醉露2018-11-29 17:16
问题解决了
#3
Jonny02012018-11-29 20:37
return 函数自己的名字就是递归
#4
rohalloway2018-11-30 18:56
程序代码:

#include <iostream>
using namespace std;

int c(int x, int y) {
    if (x < 1)
    {
        cout << "if" << endl;
        return y + 2;
    }
    else if (x % 2 == 1)
    {
        cout << "else if" << endl;
        return (y*c(x - 1, y + 1));
    }
    else
    {
        cout << "else" << endl;
        return (c(x / 2, y) * 3);
    }
}

int  main()
{
    cout << c(6, 2) << endl;

    system("pause");
    return 0;
}



得到函数执行的顺序为  1."else"   2."else if"   3."else"   4."else if"   5."if"




c(6, 2)
第一次判断进入"else"分支

return (c(x / 2, y) * 3);
=
return (c(6 / 2, 2) * 3);
=
return (c(3, 2) * 3);  #

此时c(3, 2)需要先运算






c(3, 2)
第二次判断进入"else if"分支
(y*c(x - 1, y + 1));
=
(2*c(3 - 1, 2 + 1));
=
(2*c(2, 3)); ##

此时c(2, 3)需要先运算






c(2, 3)
第三次判断进入"else"分支

return (c(x / 2, y) * 3);
=
return (c(2 / 2, 3) * 3);
=
return (c(1, 3) * 3); ###

此时c(1, 3)需要先运算







c(1, 3)
第四次判断进入"else if"分支

(y*c(x - 1, y + 1));3
=
(3*c(1 - 1, 3 + 1));
=
(3*c(0, 4)); ####

此时c(0, 4)需要先运算






c(0, 4)
第五次判断进入"if"分支

return y + 2;
=
return 4 + 2;
=
return 6;

//----------------------此时return 6;并未继续调用递归函数c,开始向上返回








第一次返回6 到(3*c(0, 4)); ####处
return (3*c(0, 4));
=
return (3*6);
=
return 18


第二次返回18到return (c(1, 3) * 3); ###处
return (c(1, 3) * 3)
=
return (18 * 3)
=
return 54

第三次返回54到return (2*c(2, 3)); ##处
return (2*c(2, 3))
=
return (2*54)
=
return 108

第四次返回到return (c(3, 2) * 3);  #处
return (c(3, 2) * 3);
=
return (108 * 3);
=
return 324

最后返回到main函数中
cout << c(6, 2) << endl;
=
cout << 324 << endl;




笨方法追踪递归


[此贴子已经被作者于2018-11-30 19:00编辑过]

1