How to print out this certain fibonacci sequence?

2019-09-14 18:12发布

问题:

public static int getFib(int num) {

        if (num < 2) {
            return num;
        }
        return getFib(num - 1) + getFib(num - 2);
    }

How can I use this code to print out this sample output like file attached with the same format of print out

回答1:

Assuming your getFib() is like this:

public static int getFib(int num) {
        if (num < 2) {
            return num;
        }
        int tmp = getFib(num - 1) + getFib(num - 2);
        return tmp;
    }

In the main() function call the getFib() function for the asked number of times and print the values returned, as:

for(i=0;i<numberOfTimes;++i){
     System.out.println(getFib(i));
}


回答2:

Try this one. This stores your result and prints it out before continuing the calculation.

 public static int getFib(int num) {
        if (num < 2) {
            return num;
        }
        int tmp = getFib(num - 1) + getFib(num - 2);
        System.out.println(tmp);
        return tmp;
    }