java fibonacci series error : not getting proper output

java fibonacci series error : not getting proper output

我正在尝试使用此程序打印斐波那契数列。我使用了 n=10(要打印的斐波那契数),我得到了 10 多个数字。请你能指出我错在哪里吗?

import java.util.*;
class myprogram{
    static int f=0,s=1,sum=0;
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        System.out.printf("Enter the number of numbers you want to print");
        int n=sc.nextInt();
        System.out.print(f+" "+s);
        fib((n-2));
    }
    static void fib(int count){
        while(count!=0)
        {
            sum=f+s;
            System.out.print(" "+sum);
            f=s;
            s=sum;
            count-=1;
            fib(count);
        }

    }
}

输入:

n=10

预期输出:

0 1 1 2 3 5 8 13 21 34

我的输出:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 ...

您的解决方案已经是迭代的,包括 while 循环。但是,您正在调用 fib 减少计数,大大增加了打印的数字数量。

删除递归调用,它会工作得很好。

你的代码是做什么的:

初始:

Iteration     f     s     sum
0             0     1      0

第一次调用 fib 函数

Iteration     f     s     sum
1             1     1      1
2             1     2      2
3             2     3      3
4             3     5      5
5             5     8      8
6             8     13     13
7             13    21     21
8             21    34     34

你的程序应该根据你的需要停在这里。但是,您通过在函数末尾添加 fib(count) 来一次又一次地递归调用 fib 函数。这就是它继续下去的原因。它将进行 7 (9-2) + 6 + 5 + 4 + 3 + 2 = 27 次迭代。