Fibonacci序列检测器Java

时间:2014-11-01 23:09:36

标签: java sequence fibonacci

我的我的Fibonacci数字程序遇到了我的Intro to Java类。它仅在我按升序键入数字时才有效。

目标:必须使用while循环,必须检测数字是否为斐波纳契数,并且必须检测序列中数字的顺序。如果它不是斐波纳契数,它必须这样说,并告诉它之间的数字。在用户退出

之前,程序还必须继续询问输入编号

输出的示例:

Please input a number for analysis >> 2
2 is a fibonacci number whose order in the sequence is 4
Please input a number for analysis >> 53
53 is not a fibonacci number 
However, it lies between the Fibonacci numbers 34 (order:10) and 55 (order:11)

我的问题:只有当我按升序输入输入数字时,程序才有效。所以例如,如果我输入5,它告诉我它是带有seq的fib数。但是当我输入2时,它表示它不是一个原始数字,而是位于Fibonacci数字3(顺序:5)和5(顺序:6)之间。当我输入55时,它告诉我它是一个原始数字。但是如果没有显示不正确的输入,我就不能输入任何低于55的数字。

我认为问题出在else if语句中,可能是(fibnext!= testnum)。或者算一下?任何人都可以指出我可能出现问题的方向吗?

import java.util.Scanner;

public class Fibonacci
{
    public Fibonacci()
    {
        int fibhigh = 1;
        int fiblow = 0;
        int count = 2;
        int fibnext = 0;
        Scanner input = new Scanner(System.in);
        boolean quit = false;

        System.out.println("Welcome to Fibonacci Sequence Dectector");
        while(!false)
        {
            System.out.print("Please input a number for analysis >> ");
            int testnum = input.nextInt();

            if(testnum < 0)
            {
                System.out.println("Please enter a positive number");
                continue;
            }
            while(fibnext < testnum)
            {
                fibnext = fibhigh + fiblow;
                fiblow = fibhigh;
                fibhigh = fibnext;
                count++;
            }
            if(fibnext == testnum)
            {
                System.out.println(testnum + " is a fibonacci number whose order in the sequence is " + count);
            }
            else if(fibnext != testnum) System.out.println(testnum + " is not a fibonacci number \nHowever, it lies between the Fibonacci numbers " + fiblow + " (order:" + (count - 1) + ") and " + fibhigh + " (order:" + count + ")");
        }
    }
}

2 个答案:

答案 0 :(得分:1)

你永远不会清除纤维,纤维和纤维。这意味着您每次都会比较最高的数字。您应该在用户输入数据之前将值设置为原始数字。

答案 1 :(得分:1)

你永远不会重置变量 int fibhigh = 1, fiblow = 0, count = 2, fibnext = 0;

您应该移动此代码段

int fibhigh = 1;
int fiblow = 0;
int count = 2;
int fibnext = 0;

在循环开始时:

while (!false) {  }