How to print out this certain fibonacci sequence?

心已入冬 提交于 2019-12-12 04:44:58

问题


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


来源:https://stackoverflow.com/questions/42931865/how-to-print-out-this-certain-fibonacci-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!