[英]C++ incrementing in a recursive function
我在尋找遞歸 function 樣本時發現了這個帶有 grepper 的代碼片段。 我了解 refursive 部分,function 如何調用自身 - 1 直到它到達基本情況,但是,我不明白 else 中的最后一行。 只是想弄清楚最后一行如何將數字返回到 go 直到它回到起始值。 代碼中沒有任何內容將其設置為 +1,而且,當它返回時,它是調用 function 本身還是我不知道的規則? 只是想把我的頭腦圍繞這里的邏輯。
void PrintTest(int test)
{
if (test < 1)
{
return; // Exit condition, known as "base case"
}
else
{
cout << test << " ";
PrintTest(test-1);
cout << test << " ";
}
}
int main()
{
int a;
cout << "Enter a number prefarably between 2 and 9: ";
cin >> a;
PrintTest(a);
我知道這可能是一個愚蠢的問題,但只是想了解為什么“cout << test <<”“;” 增加備份的數字就是這樣。
它不會“增加備份的數量”。
在遞歸步驟之后,處理從中斷處繼續。 所以你只是看到“較低”的堆棧幀完成了它們的處理。
以下是事件的順序,從上到下:
PrintTest(3) PrintTest(2) PrintTest(1) PrintTest(0)
===============================================================================
cout << 3 << " ";
PrintTest(3-1); cout << 2 << " ";
PrintTest(2-1); cout << 1 << " ";
PrintTest(1-1); return;
cout << 1 << " ";
cout << 2 << " ";
cout << 3 << " ";
考慮這個更簡單的情況:
void foo(int x) {
std::cout << x << '\n';
bar(x-1);
std::cout << x << '\n';
}
我想您可以毫無問題地預測例如foo(3)
的 output :
3
... any output from bar(2) comes here ...
3
現在將bar
替換為foo
並為遞歸添加一個停止,您與PrintTest
相同。
如您所願,您可以嘗試按引用傳遞。 對已通過test
的所有更改都引用了原始a
。
void PrintTest(int& test) // pass-by-reference
{
if (test < 1)
{
return;
}
else
{
cout << test << " ";
test -= 1; // decrease self
PrintTest(test); // and pass reference
cout << test << " ";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.