【发布时间】: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