2014-10-31 41 views
-2

我不知道如何打印,斐波納契數列中的數字是(第n個數字)。粗體文本是我遇到的麻煩,我必須使用while循環。斐波納契數列中的第n個數字

請輸入用於分析的數>> 1 1是Fibonacci數其順序的序列中是兩個2和3

請輸入用於分析>>一個數56 55是不是一個斐波那契數。 然而56是11和12之間

這裏是我的代碼

import java.util.Scanner; 
public class While 
{ 
public static void main(String[] args) 
{ 
System.out.println("Welcome to the Fibonacci Sequence Detector\n\n"); 
Scanner in = new Scanner(System.in);  
System.out.print("Please input a number for analysis: "); 
int input = in.nextInt(); 

int fib = 0; 
int fib1 = 1; 
int n; 
while(true) 
{ 
    n=fib+fib1; 
    if(input == fib1) 
    { 
     fib = -1; 
     break; 
    } 
    if(input>fib1 && input < n) 
    { 
     break; 
    } 
    fib = fib1; 
    fib1=n; 
} 
if (fib == -1 || input == 0) 
    System.out.println(input+" is a Fibonacci number whose order in the sequence is "); 
    else 
    System.out.println(input+ " is not a Fibonacci number"); 


} 
} 
+1

看起來像一個家庭作業;) – 1ac0 2014-10-31 20:45:01

+0

是啊我堅持閱讀纖維。起。 – daman 2014-10-31 20:46:26

回答

0

我能想到的最簡單的方法是讓您通過增加每次計數器變量。

while(true) { 
    count++; 
... 
} 
... 
System.out.println(input+" is a Fibonacci number whose order in the sequence is "+count); 

作爲一個側面說明,有沒有你使用while(true)理由嗎?通常有一種方法可以跟蹤您希望停止循環的條件。 (我被教導說while(true)並不總是錯的,但它通常是。):)

+0

我以爲內循環必須是真的嗎? – daman 2014-10-31 20:51:50

+0

感謝它的工作! – daman 2014-10-31 20:59:46

+1

當用戶輸入相當時,我將如何退出程序? '布爾上=真 而(上){// 提示用戶輸入 如果(userInput.equals( 「退出」)){ 上= FALSE; }' – daman 2014-10-31 21:43:55

0

斐波那契數列有一個封閉的形式,所以沒有必要搜索到您感興趣的數字。可以直接計算斐波納契數,並找出序列中給定數的位置。

public class Fibi { 
    public static void main(String[] args) { 
     double root5 = Math.sqrt(5); 
     double phi = (1.0 + root5)/2.0; 
     double log_phi = Math.log(phi); 

     for (String s : args) { 
      long fib = Long.parseLong(s); 
      long n = (long) Math.floor(Math.log(fib * root5)/log_phi); 
      long nth = Math.round(Math.pow(phi, n)/root5); 
      long next = Math.round(Math.pow(phi, n+1)/root5); 
      if (fib == nth) { 
       System.out.printf("%d is a Fibonacci number whose order is %d.%n", 
        fib, n); 
      } else if (fib == next) { 
       System.out.printf("%d is a Fibonacci number whose order is %d.%n", 
        fib, n+1); 
      } else { 
       System.out.printf("%d is not a Fibonacci number. " + 
        "However, %d is between %d and %d.%n", fib, fib, n, n+1); 
      } 
     } 
    } 
} 

如果用java Fibi 102334155運行此程序,它輸出:

102334155 is a Fibonacci number whose order is 40. 

請注意,我還沒有實現1,其序列中出現兩次,而且很容易被作爲特例處理,我稍微改變了指數的編號。你在第2和第3位有1個,第11位有第55個,這意味着你正在考慮將0作爲斐波那契數列中的第一個數字,我通常認爲它定義爲從1 1開始。但是,這可以通過一個小的改變來處理。

+0

謝謝!我改變了我的代碼,它完美的工作,但當用戶輸入「退出」@DavidConrad時,我不能退出程序 – daman 2014-10-31 22:37:23