2017-10-07 59 views
-3

爲了不遍歷無限循環,我正在遞減while事件中的count變量,儘管它在使用遞歸函數。在while循環中使用遞歸函數即使遞減計數值也會無限循環

public class RFibonocci{ 
    static int n1=0,n2=1,count; 
    public RFibonocci(){ 
     System.out.println("Enter the fibo series:"); 
     Scanner scr=new Scanner(System.in); 
     count=scr.nextInt(); 
     System.out.println("Series is:"); 
     System.out.println(n1+"\n"+n2); 
     fibo(count-2); 
    } 
    public static void fibo(int count){ 
     while(count>0){ 
      int n3=n1+n2; 
      System.out.println(n3); 
      n1=n2; 
      n2=n3; 
      count-=1; 
      fibo(count); 
     } 
    } 
    public static void main(String...args){ 
     new RFibonocci(); 
    } 

} 
+0

這不是無限的。非常非常非常長。 –

+0

歡迎來到SO。哪個'數值'導致它運行到無窮大? – c0der

回答

0

你不應該有while遞歸。 (看起來它只是繼續前進,因爲調用通過全局變量共享狀態,不要這樣做:正如你所看到的,這使得它很難調試。)

0

首先,我會將初始查詢更改爲用戶輸入「要計算的斐波那契條款數量」或類似的東西。

我也會考慮刪除while語句併爲fibo()遞歸的基本情況插入if語句。

在fibo()函數中包含while語句會產生問題。不僅在while循環中調用了fibo()函數,而且while循環將在內部fibo()返回後繼續運行。

希望這會有所幫助。