【问题标题】:Fibonacci Last Number斐波那契最后一个数字
【发布时间】:2015-10-07 21:02:21
【问题描述】:

我已经完成了这部分代码,我正试图让它只打印最后一个斐波那契数,而不是全部。我该怎么做呢?我知道整个程序还没有完成,但我只需要知道如何打印最后一个数字,例如,当您选择选项 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);

} 
}}}

【问题讨论】:

  • 为什么不直接省略 for 循环中的 print 语句,将 xCurr 的值打印为程序中的最后一个表达式?
  • 我该怎么做呢?我仍然需要打印语句。

标签: fibonacci


【解决方案1】:

基本上只要修改代码如下

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-29
    • 2020-08-26
    • 2020-01-18
    • 2015-06-05
    • 2014-05-23
    • 2014-05-03
    • 1970-01-01
    相关资源
    最近更新 更多