2017-04-22 46 views
-2

我正在解決的問題是用戶輸入一個數字,然後從該數字倒數5,直到我達到一個負數,然後計數備份5,直到我回到那個數字。我必須這樣做,只使用遞歸而沒有循環。該代碼接縫大部分右邊工作,直到值爲0這種遞歸發生了什麼?我需要倒計時和使用只有遞歸/無循環備份

void Func(int num, int base, bool flipped) 
{ 
    cout << num << endl; 

    if (flipped == false && num > 1) 
    { 
     Func(num - 5, base, flipped); 
    } 

    flipped = true; 

    if (num < base) 
    { 
     Func(num + 5, base, true); 
    } 

    return; 
} 

我是從上面的代碼獲得具有17的輸入是所述的輸出翻轉左右背部: 17, 12, 7, 2, -3, 2, 7, 12, 17, 7, 12, 17, 12, 17, 17.

由於某種原因,看起來第二次遞歸存在問題。到目前爲止我嘗試過的方法是將bool靜態化,並在任何地方添加return語句。感謝您的任何幫助!

+4

請[讓你的橡皮鴨子預約(https://en.wikipedia.org/wiki/Rubber_duck_debugging)。 –

+0

你使用什麼樣的調試器?如果它是Visual C++,調用堆棧窗格可以幫助您。 – sergiol

+0

記下你回到的地方,以及你......不在的地方。當所有其他的遞歸調用完成時會發生什麼,並且您回到那一點? –

回答

0

試試這個:

#include <cstdlib> 
#include <iostream> 

int recount(int num) 
{ 
    std::cout<<num<<'\n'; \\Prints the current num 
    if(num >= 0) \\checks that num is positive 
    { 
    \\recursively call the function counting down by 5 
    std::cout<<recount(num-5)<<'\n'; 
    } 
    \\count up by 5 as we go back up 
    return num + 5; 
} 

int main() 
{ 
    recount(17); \\ gives desired output 
    return EXIT_SUCCESS; 
}