Fibonacci sequence refers to: the last term of the sequence is equal to the sum of the first two terms. In the code, we use a[i]=a[i-1] a[i-2] is implemented.
Typical problem of rabbits giving birth to babies
Classical problem: There is a pair of rabbits that give birth to babies every month from the 3rd month after birth. A pair of rabbits. After the rabbit reaches the third month, another pair will be born every month. Assuming that each pair of rabbits survives, program to find the number of pairs of rabbits each month.
Related video tutorial recommendations: java teaching video
Code example:
Core code, Fibonacci sequence (the latter term is equal to the first two terms and):
public static void getTuTu(int[] tutu, int n) { if (n == 1) { System.out.println("第一个月兔子对数为1"); } else if (n == 2) { System.out.println("第二个月兔子对数为1"); } else { tutu[0] = 1; tutu[1] = 1; System.out.println("第1个月兔子对数为1"); System.out.println("第2个月兔子对数为1"); for (int i = 2; i < n; i++) { tutu[i] = tutu[i - 1] + tutu[i - 2];//数组记录兔子对数 System.out.println("第" + (i + 1) + "个月的兔子对数为" + tutu[i]); } } }
Complete code:
package day191125; import java.util.Scanner; public class TuZi { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (true) { System.out.println("========="); System.out.println("输入求第几个月的兔子:"); int n = input.nextInt(); if (n <= 0) { System.out.println("输入错误重新输入"); continue; } int[] tutu = new int[n]; getTuTu(tutu, n); } } public static void getTuTu(int[] tutu, int n) { if (n == 1) { System.out.println("第一个月兔子对数为1"); } else if (n == 2) { System.out.println("第二个月兔子对数为1"); } else { tutu[0] = 1; tutu[1] = 1; System.out.println("第1个月兔子对数为1"); System.out.println("第2个月兔子对数为1"); for (int i = 2; i < n; i++) { tutu[i] = tutu[i - 1] + tutu[i - 2]; System.out.println("第" + (i + 1) + "个月的兔子对数为" + tutu[i]); } } } }
Running result graph:
Of course the implementation method There is more than this one, here is just a brief introduction to one method.
If you want to know more related tutorials, you can visit java introductory learning. Everyone is welcome to discuss and learn together.
The above is the detailed content of Simple implementation method of Fibonacci sequence in java. For more information, please follow other related articles on the PHP Chinese website!