简体   繁体   中英

java fibonacci series error : not getting proper output

I am trying to print Fibonacci series with this program. I used n=10 (number of fibonacci numbers to print), I got more than 10 numbers. Please could youu point me out where I am wrong?

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);
        }

    }
}

Input:

n=10

Expected output:

0 1 1 2 3 5 8 13 21 34

My output:

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 ...

Your solution is already iterative, including the while loop. However, you are calling fib with the reduced count, greatly increasing the number of numbers printed.

Remove the recursive call, and it will work just fine.

What your code doing is:

Initial:

Iteration     f     s     sum
0             0     1      0

First call of fib function

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

You program should stop here according to what you want. However, you keep calling the fib function again and again recursively by adding fib(count) at the end of your function. That's why it goes on. It will make 7 (9-2) + 6 + 5 + 4 + 3 + 2 = 27 more iterations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM