2014-03-27 56 views
0

我正在使用下面的方法來獲得fabonacci數列系列高達100(基於用戶輸入),但輸出包含一些負面垃圾數量。什麼是我的斐波那契邏輯中的錯誤

public static void getIterativeFibonacci(int number) { 
    if (number == 1) { 
     System.out.println(number); 
    } 
    int fibo1 = 1, fibo2 = 1, fibonacci = 1; 
    for (int i = 2; i <= number; i++) { 
     fibonacci = fibo1 + fibo2; 
     fibo1 = fibo2; 
     fibo2 = fibonacci; 
     if (fibonacci <= number) { 
      System.out.println("==>"+fibonacci); 
     } 
    } 
} 

你能幫我找出上面的邏輯問題。

UPDATE:

我得到了修復:

public static void getIterativeFibonacci(long number) { 
    if (number == 1) { 
     System.out.println(number); 
    } 
    long fibo1 = 1, fibo2 = 1, fibonacci = 1; 
    for (int i = 2; i <= number; i++) { 
     fibonacci = fibo1 + fibo2; 
     if (fibonacci >= number) { 
      break; 
     } 
     fibo1 = fibo2; 
     fibo2 = fibonacci; 
     System.out.println("==>" + fibonacci); 
    } 
} 
+0

輸出:100 ==> 2 ==> 3 ==> 5 ==> 8 ==> 13 ==> 21 ==> 34 ==> 55 ==> 89 – user1102123

+1

您的代碼中有兩個「修復」 - 將參數類型更改爲「long」和「break」循環。哪一個是修補程序,還是兩者兼而有之? – ChiefTwoPencils

回答

0
public static void getIterativeFibonacci(int number) { 
    if (number == 1) { 
     System.out.println(number); 
    } 
    int fibo1 = 0, fibo2 = 1, fibonacci = 0; 
    for (int i = 2; i <= number; i++) { 
     System.out.print(fibo1) 
     fibonacci = fibo1 + fibo2; 
     fibo1 = fibo2; 
     fibo2 = fibonacci; 
    if (fibonacci <= number) { 
     System.out.println("==>"+fibonacci); 
    } 
} 

}

試試這個

1

打破for循環,一旦你達到了數限制。

public static void getIterativeFibonacci(int number) { 
     if (number == 1) { 
      System.out.println(number); 
     } 
     int fibo1 = 1, fibo2 = 0, fibonacci = 1; 
     for (int i = 2; i <= number; i++) { 
      fibonacci = fibo1 + fibo2; 
      fibo1 = fibo2; 
      fibo2 = fibonacci; 
      if (fibonacci <= number) { 
       System.out.println("==>"+fibonacci); 
      }else{ 
       break; 
      } 
     } 
    }