递归在c ++因子程序 [英] Recursion in c++ Factorial Program
问题描述
hello我有一段代码,我基于一些其他递归和阶乘程序
编码,但我的问题是,我真的很困惑,如何存储的值,保留它,然后返回它在end
hello i have this piece of code that i coded based on some other recursion and factorial programs but my problem is that i am really confused as to how it stored the value and kept it and then returned it at the end
int factorialfinder(int x)
{
if (x == 1)
{
return 1;
}else
{
return x*factorialfinder(x-1);
}
}
int main()
{
cout << factorialfinder(5) << endl;
}
所以5进去,再次调用它的函数,乘以4一次又一次,然后它得到一个,它返回阶乘答案
so 5 goes in, and gets multiplied by 4 by calling its function again and again and again, then it gets to one and it returns the factorial answer
为什么?我不知道它是如何存储的,为什么返回1返回实际的答案,它真正做什么?
why? i have no idea how it got stored, why is return 1 returning the actual answer, what is it really doing?
推荐答案
img src =http://i.stack.imgur.com/q2Zkv.gifalt =来自IBM开发人员网站的递归图片>
资料来源:Image取自: IBM开发人员网站
Source: Image is taken from: IBM Developers website
只要看看上面的图片,你会明白更好。
Just take a look at the picture above, you will understand it better. The number never gets stored, but gets called recursively to calculate the output.
所以当你调用事实(4)时,当前堆栈用于存储每个参数为递归调用发生在factorialfinder(1)。所以计算如下:5 * 4 * 3 * 2 * 1。
So when you call the fact(4) the current stack is used to store every parameter as the recursive calls occur down to factorialfinder(1). So the calculation goes like this: 5*4*3*2*1.
int factorialfinder(int x)
{
if (x == 1) // HERE 5 is not equal to 1 so goes to else
{
return 1;
}else
{
return x*factorialfinder(x-1); // returns 5*4*3*2*1 when x==1 it returns 1
}
}
希望这有帮助。
这篇关于递归在c ++因子程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!