2015-09-28 32 views
0

目前我想要做的是將餘下的循環轉換爲遞歸函數。之前,我對R1,R2和R3有一個for循環,根據它們的值產生總支出。如何將剩餘的循環更改爲遞歸函數?

例如

1 1 1 payout is 1 

1 1 2 payout is 1 

1 1 3 payout is 1 

....... 

3 3 3 payout is 3 

我能第一個轉換爲環(R1)爲遞歸函數和我的代碼仍然編譯就好了。我現在遇到的問題是將剩餘的for循環(R2和R3)轉換爲遞歸函數。我試圖將R1的格式複製到R2和R3上,但由於每個變量都在其自己的函數中,所以我有聲明問題。

我應該採取哪些措施來正確處理這個問題?

這裏是我當前的工作代碼的遞歸函數R1:

int totalFunc(int R1, int R2, int R3); 

void loopR1(int R1, int upto); 

int R2, R3 = 1; 
int totalScore = 0; 

int main() 
{ 
    loopR1(1, 3); 
    return 0; 
} 

void loopR1(int R1, int upto) 
{ 
    if (R1 <= upto){ 
     for(R2 = 1; R2 <= 3; R2++){ 
     for(R3 = 1; R3 <= 3; R3++){ 
      printf(" %d %d %d Total Score is: %d\n\n", R1, R2, R3, totalFunc(R1,R2,R3)); 
     } 
     } 

     loopR1(R1+1, upto); 
    } 
} 

int totalFunc(int R1, int R2, int R3) 
{ 
    int totalScore = R1; 

    if (R2 < R1){ 
     totalScore += R2; 
     if (R3 < R2){ 
     totalScore += (2*R3); 
     } 

     else{ 

      if (R3 < R1){ 
      totalScore += R3; 
     } 
     } 
    } 

     else{ 

     if (R3 < R1){ 
     totalScore += R3; 
     } 
    } 

    return totalScore; 
} 

編輯:

我加入了更正由R薩胡但是我現在遇到的問題是建議R1不增加程序崩潰而不是成功返回0.我相信這個錯誤與我下面粘貼的代碼段有關。

int totalFunc(int R1, int R2, int R3); 

void loopR1(int R1, int upto); 
void loopR2(int R1, int R2, int upto); 

int R3; 
int totalScore = 0; 

int main() 
{ 
    loopR1(1, 3); 
    loopR2(1, 1, 3); 

    return 0; 
} 
+0

正確縮進和格式化這個混亂! – Olaf

+0

我以爲我的格式是正確的。你的意思是代碼格式或其在本網站上的顯示方式? –

+1

嗯,你是對的。只是看看你的本地硬盤,它的格式完美。 'else {if'? – Olaf

回答

0

下一級遞歸函數,我們稱之爲loopR2,需要有論點R1R2upto

void loopR2(int R1, int R2, int upto) 
{ 
    if (R2 <= upto){ 
     for(R3 = 1; R3 <= 3; R3++){ 
     printf(" %d %d %d Total Score is: %d\n\n", R1, R2, R3, totalFunc(R1,R2,R3)); 
     } 
     loopR2(R1, R2+1, upto); 
    } 

} 

void loopR1(int R1, int upto) 
{ 
    if (R1 <= upto){ 
     loopR2(R1, 1, 3); 
     loopR1(R1+1, upto); 
    } 
} 

我會給你找出如何實施loopR3

+0

我添加了你的更正,並相信我正在對整體代碼做出正確的修改,但是現在我遇到的問題是R1不會增加超過1,並且程序崩潰。我上面發佈的修改,除了上面提到的代碼之外。 –

+0

有沒有一個特定的術語我應該繼續研究這種遞歸形式?爲了更好地理解代碼,我試圖在網上找到更多的信息,但是我很難找到與這種遞歸函數形式密切相關的材料。 –

+0

搜索尾部遞歸。 –