2015-10-07 58 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。