Java实例05-斐波那契数列
斐波那契数列指的是这样一个数列 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……
特别指出:第0项是0,第1项是第一个1。
代码实现:
import java.util.Scanner; /** * @author: TSCCG * @date: 2021/5/17 */ public class Fibonacci { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入要查的数:"); System.out.println(fibonacci(sc.nextInt())); } public static int fibonacci(int num) { if (num < 1) { System.out.println("必须为正整数"); return -1; } else if (num == 1) { return 1; } else if (num == 2) { return 1; } else { return fibonacci(num - 1) + fibonacci(num - 2); } } }