問題描述
你好,我有一段基于其他遞歸和階乘程序編寫的代碼但我的問題是我真的很困惑它是如何存儲值并保留它然后在最后返回它
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 進(jìn)入,通過一次又一次地調(diào)用它的函數(shù)被乘以 4,然后它得到 1 并返回階乘答案
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
為什么?我不知道它是如何存儲的,為什么 return 1 返回實(shí)際答案,它到底在做什么?
why? i have no idea how it got stored, why is return 1 returning the actual answer, what is it really doing?
推薦答案
來源:圖片取自:IBM 開發(fā)人員網(wǎng)站
看看上面的圖片,你會更好地理解它.該數(shù)字永遠(yuǎn)不會被存儲,而是被遞歸調(diào)用以計算輸出.
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.
因此,當(dāng)您調(diào)用 fact(4) 時,當(dāng)前堆棧用于存儲每個參數(shù),因為遞歸調(diào)用發(fā)生到 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
}
}
希望這會有所幫助.
這篇關(guān)于C++ 階乘程序中的遞歸的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!