2014-10-31 42 views
-2

我不知道如何打印,斐波纳契数列中的数字是(第n个数字)。粗体文本是我遇到的麻烦,我必须使用while循环。斐波纳契数列中的第n个数字

请输入用于分析的数>> 1 1是Fibonacci数其顺序的序列中是两个2和3

请输入用于分析>>一个数56 55是不是一个斐波那契数。 然而56是11和12之间

这里是我的代码

import java.util.Scanner; 
public class While 
{ 
public static void main(String[] args) 
{ 
System.out.println("Welcome to the Fibonacci Sequence Detector\n\n"); 
Scanner in = new Scanner(System.in);  
System.out.print("Please input a number for analysis: "); 
int input = in.nextInt(); 

int fib = 0; 
int fib1 = 1; 
int n; 
while(true) 
{ 
    n=fib+fib1; 
    if(input == fib1) 
    { 
     fib = -1; 
     break; 
    } 
    if(input>fib1 && input < n) 
    { 
     break; 
    } 
    fib = fib1; 
    fib1=n; 
} 
if (fib == -1 || input == 0) 
    System.out.println(input+" is a Fibonacci number whose order in the sequence is "); 
    else 
    System.out.println(input+ " is not a Fibonacci number"); 


} 
} 
+1

看起来像一个家庭作业;) – 1ac0 2014-10-31 20:45:01

+0

是啊我坚持阅读纤维。起。 – daman 2014-10-31 20:46:26

回答

0

我能想到的最简单的方法是让您通过增加每次计数器变量。

while(true) { 
    count++; 
... 
} 
... 
System.out.println(input+" is a Fibonacci number whose order in the sequence is "+count); 

作为一个侧面说明,有没有你使用while(true)理由吗?通常有一种方法可以跟踪您希望停止循环的条件。 (我被教导说while(true)并不总是错的,但它通常是。):)

+0

我以为内循环必须是真的吗? – daman 2014-10-31 20:51:50

+0

感谢它的工作! – daman 2014-10-31 20:59:46

+1

当用户输入相当时,我将如何退出程序? '布尔上=真 而(上){// 提示用户输入 如果(userInput.equals( “退出”)){ 上= FALSE; }' – daman 2014-10-31 21:43:55

0

斐波那契数列有一个封闭的形式,所以没有必要搜索到您感兴趣的数字。可以直接计算斐波纳契数,并找出序列中给定数的位置。

public class Fibi { 
    public static void main(String[] args) { 
     double root5 = Math.sqrt(5); 
     double phi = (1.0 + root5)/2.0; 
     double log_phi = Math.log(phi); 

     for (String s : args) { 
      long fib = Long.parseLong(s); 
      long n = (long) Math.floor(Math.log(fib * root5)/log_phi); 
      long nth = Math.round(Math.pow(phi, n)/root5); 
      long next = Math.round(Math.pow(phi, n+1)/root5); 
      if (fib == nth) { 
       System.out.printf("%d is a Fibonacci number whose order is %d.%n", 
        fib, n); 
      } else if (fib == next) { 
       System.out.printf("%d is a Fibonacci number whose order is %d.%n", 
        fib, n+1); 
      } else { 
       System.out.printf("%d is not a Fibonacci number. " + 
        "However, %d is between %d and %d.%n", fib, fib, n, n+1); 
      } 
     } 
    } 
} 

如果用java Fibi 102334155运行此程序,它输出:

102334155 is a Fibonacci number whose order is 40. 

请注意,我还没有实现1,其序列中出现两次,而且很容易被作为特例处理,我稍微改变了指数的编号。你在第2和第3位有1个,第11位有第55个,这意味着你正在考虑将0作为斐波那契数列中的第一个数字,我通常认为它定义为从1 1开始。但是,这可以通过一个小的改变来处理。

+0

谢谢!我改变了我的代码,它完美的工作,但当用户输入“退出”@DavidConrad时,我不能退出程序 – daman 2014-10-31 22:37:23