【发布时间】:2016-01-05 10:10:53
【问题描述】:
在我的一个 java 程序中,我试图读取一个数字,然后使用黄金分割率 (1.618034) 来找到下一个最小的斐波那契数它的索引。例如,如果我输入100000,我应该返回“大于 100000 的最小斐波那契数是第 26 位,其值为 121393”。
程序还应该按索引计算斐波那契数(下面代码中的case 1),我到目前为止已经编码,但我不知道如何解决上述问题(case 2)。我有一个糟糕的老师,我真的不明白我需要做什么。我不是要代码,只是一步一步地为case 2 做些什么。我不能使用递归。感谢您的任何帮助。我真的很讨厌这个问题。
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 = 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);
break;
case 2:
System.out.print("Enter the target value (>1): ");
int value = scan.nextInt();
}
}
}
【问题讨论】:
-
您可以将其放入
while循环中并计算斐波那契数,直到它大于value。 -
就像我说的,我真的不明白如何进行整个计算。我正在尽我最大的努力,但我知道通过 while 循环你有条件和语句,但是我应该为语句计算放什么?
标签: fibonacci