Three java programming methods are used to implement the Fibonacci series and java Fibonacci
Requirement: write a program to output the first 20 items of the Fibonacci series on the console, with a line break for each output of five
// Java programming: three methods to implement the Fibonacci series
// Method 1:
Public class Demo2 {// define three variable methods: public static void main (String [] args) {int a = 1, B = 1, c = 0; System. out. println ("the first 20 items of the Fibonacci series are:"); System. out. print (a + "\ t" + B + "\ t"); // I <= 18 for (int I = 1; I <= 18; I ++) {c = a + B; a = B; B = c; System. out. print (c + "\ t"); if (I + 2) % 5 = 0) System. out. println ();}}}
// Java programming: three methods to implement the Fibonacci series
// Method 2:
Public class Demo3 {// define the array method public static void main (String [] args) {int arr [] = new int [20]; arr [0] = arr [1] = 1; for (int I = 2; I <arr. length; I ++) {arr [I] = arr [I-1] + arr [I-2];} System. out. println ("the first 20 items of the Fibonacci series are as follows:"); for (int I = 0; I <arr. length; I ++) {if (I % 5 = 0) System. out. println (); System. out. print (arr [I] + "\ t ");}}}
// Java programming: three methods to implement the Fibonacci series
// Method 3:
Public class Demo4 {// use the recursive method private static int getFibo (int I) {if (I = 1 | I = 2) return 1; else return getFibo (I-1) + getFibo (I-2);} public static void main (String [] args) {System. out. println ("the first 20 items of the Fibonacci series are:"); for (int j = 1; j <= 20; j ++) {System. out. print (getFibo (j) + "\ t"); if (j % 5 = 0) System. out. println ();}}}
The essence of this rabbit question is the Fibonacci series: A rabbit was born every month from the first 3rd months after birth, and a rabbit was born every month after the third month, if rabbits do not die, how many rabbits are there every month ?, Now we can solve this puzzle from the perspectives of variables, arrays, and recursion. Of course, there are other ways to solve the same problem with different ideas, it is also an exercise for the comprehensive use of knowledge.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.