我的斐波纳契逻辑中的错误是什么

时间:2014-03-27 05:21:01

标签: java data-structures

我使用下面的方法将fabonacci数字序列达到100(基于用户输入),但输出包含一些负的垃圾编号。

public static void getIterativeFibonacci(int number) {
    if (number == 1) {
        System.out.println(number);
    }
    int fibo1 = 1, fibo2 = 1, fibonacci = 1;
    for (int i = 2; i <= number; i++) {
        fibonacci = fibo1 + fibo2;
        fibo1 = fibo2;
        fibo2 = fibonacci;
        if (fibonacci <= number) {
            System.out.println("==>"+fibonacci);
        }
    }
}

请您帮我解决上述逻辑中的问题。

更新:

我得到了修复:

public static void getIterativeFibonacci(long number) {
    if (number == 1) {
        System.out.println(number);
    }
    long fibo1 = 1, fibo2 = 1, fibonacci = 1;
    for (int i = 2; i <= number; i++) {
        fibonacci = fibo1 + fibo2;
        if (fibonacci >= number) {
            break;
        }
        fibo1 = fibo2;
        fibo2 = fibonacci;
        System.out.println("==>" + fibonacci);
    }
}

2 个答案:

答案 0 :(得分:1)

一旦达到数字限制,就打破for循环。

public static void getIterativeFibonacci(int number) {
        if (number == 1) {
            System.out.println(number);
        }
        int fibo1 = 1, fibo2 = 0, fibonacci = 1;
        for (int i = 2; i <= number; i++) {
            fibonacci = fibo1 + fibo2;
            fibo1 = fibo2;
            fibo2 = fibonacci;
            if (fibonacci <= number) {
                System.out.println("==>"+fibonacci);
            }else{
                break;
            }
        }
    }

答案 1 :(得分:0)

public static void getIterativeFibonacci(int number) {
    if (number == 1) {
        System.out.println(number);
    }
    int fibo1 = 0, fibo2 = 1, fibonacci = 0;
    for (int i = 2; i <= number; i++) {
        System.out.print(fibo1)
        fibonacci = fibo1 + fibo2;
        fibo1 = fibo2;
        fibo2 = fibonacci;
    if (fibonacci <= number) {
        System.out.println("==>"+fibonacci);
    }
}

}

尝试这个