Fibonacci最后号码

时间:2015-10-07 21:02:22

标签: fibonacci

我完成了这部分代码,我试图让它只打印最后一个Fibonacci数字,而不是全部。我该怎么做呢?我知道整个程序还没有完成,但我只需要知道如何打印最后一个数字,例如,当你选择选择1,然后输入“30”作为索引你应该只得到832040的输出而不是每个斐波那契数到30.谢谢!

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 个答案:

答案 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。