2015-10-07 93 views
-2

我已經完成了這部分代碼,並且試圖讓它打印出最後一個Fibonacci數字,而不是所有數字。我應該如何去做這件事?我知道整個程序還沒有完成,但我只需要知道如何打印最後一個數字,例如當您選擇選項1時,然後輸入「30」作爲索引,您應該只輸出832040,而不是每斐波那契數到30.謝謝!Fibonacci Last Number

import java.util.Scanner; 

public class Fibonacci { 

public static void main(String args[]) { 
    Scanner scan = new Scanner(System.in); 

    System.out.println("This is a Fibonacci sequence generator"); 
    System.out.println("Choose what you would like to do"); 
    System.out.println("1. Find the nth Fibonacci number"); 
    System.out.println("2. Find the smallest Fibonacci number that exceeds user given value"); 
    System.out.println("3. Find the two Fibonacci numbers whose ratio is close enough to the golden number"); 

    System.out.print("Enter your choice: "); 
    int choice = scan.nextInt(); 
    int xPre = 0; 
    int xCurr = 1; 
    int xNew; 

    switch (choice) 
    { 
     case 1: 
      System.out.print("Enter the target index to generate (>1): "); 
      int index = scan.nextInt(); 

      for (int i = 2; i<=index; i++) 
      {xNew = xPre + xCurr; 
      xPre = xCurr; 
      xCurr = xNew; 
     System.out.println("The " + index + "th number Fibonacci number is " + xNew); 

} 
}}} 
+1

爲什麼不直接在for循環中省略print語句並將xCurr的值作爲程序中的最後一個表達式來打印呢? –

+0

但我該怎麼做?我仍然需要打印聲明。 –

回答

0

基本上只是修改代碼如下

switch (choice) 
{ 
    case 1: 
     System.out.print("Enter the target index to generate (>1): "); 
     int index = scan.nextInt(); 

     for (int i = 2; i<=index; i++) 
     {xNew = xPre + xCurr; 
     xPre = xCurr; 
     xCurr = xNew;  
} 
System.out.println("The " + index + "th number Fibonacci number is " + xNew); 

由於xNew變量是最後修改以容納該索引的值(例如 - 30)它應該顯示的最終值作爲單獨832040。