2012-09-15 45 views
3

我正在研究一個使用遞歸函數的程序。如何退出遞歸函數?

我的問題是當遞歸函數的工作完成時,控件轉移到下一個函數,它在完成下一個函數的工作後返回遞歸函數。

我需要一些代碼,可以強制控制被轉回功能。我不想退出我的程序。

public void function1(a, num) 
{ 
    if(a >= num) 
    { 
    if(a > num) 
     function1(a, num); 
    else if(a == num) 
    { 
     a++; 
     function1(a, num) 
    } 
    } 
    else 
    function2(a, num) 
} 

public void function2(a, num) 
{ 
    //print result; 
} 

每次我打電話function1,我表演的變量anum一些變化。但問題是,在某些情況下,當function2被調用時,控制權再次傳遞給function1。你能否提供一些防止這種情況的代碼?它是我設計的時間表生成器的一部分。

+7

對於最初'a> num'的情況,您的遞歸不會停止,因爲您不會在遞歸步驟之間更改任何內容。嘗試自己追蹤代碼,說a = 1,num = 0。 – Vlad

回答

2

將一個,每當你想返回基地

2

這個版本的功能的工作方式完全相同。

public void function1(a, num) 
{ 
    if (a < num) 
    { 
     function2(a, num); 
    } 
    else 
    { 
     function1((a > num) ? a : a + 1, num); 
    } 
} 

public void function2(a, num) 
{ 
    //print result; 
} 

只是爲了您的信息:如果 a傳遞,比num越大,則該函數將ininitely遞歸,使用相同的參數列表function1(a, num)的efective調用,因此它永遠不會返回導致掛斷並最終在某個時刻出現堆棧溢出。

1

您需要將其更改爲:

public void function1(a,num) 
{ 
    if(a>num) 
    { 
     //Increment num or decrease a here, otherwise the recursion never ends 
     function1(a,num); 
     return; //Each time the method does a recursion, it stops to execute itself with 
     // a new set of arguments, but when one of them decide it's over, all the 
     // instances of the method will resume one by one, so if you don't return, 
     // it executes the rest of function1. 
    } 
    else if(a==num) 
    { 
     a++; //You probably don't want to do that, this a==num case should be merged 
     // with a>num. Can you see why? 
     function1(a,num) 
     return; 
    } 
    else 
     function2(a,num) 
} 

public void function2(a,num) 
{ 
//print result; 
} 
+2

我可能錯過了一些東西,但這些'return'語句如何改變任何東西?沒有它們,流將跳過所有'else'塊,並在函數結束時結束。 –

+0

如果最初使用'a> num',這又是無限遞歸 - 儘管它與OP的代碼邏輯相匹配。 – Vlad

+0

@Vlad看到我在代碼 –

0

或許,如果你只是進行了直循環的代碼會更簡單。

while (a <= num) 
{ 
    function2(a, num); 
    a++; 
}