package cn.dzp.flyroc.offer; import java.util.Scanner; public class FieBoNaQieDemo { /*題目描述:如今要求一输入一个整数n,请你输出斐波那契数列的第n项。n <= 39*/ /*例如:一、一、二、三、五、八、1三、21就是一个斐波那契数列,前两项之和等于后一项*/ /*思路:递归的效率低,使用循环方式*/ //代码实现 public static long feibonaqie(int n){ long result = 0; //定义两数之和 long preOne = 0; //定义第一个元素 long preTwo = 1; //定义第二个元素 if (n == 0){ //若是 n = 0 return preTwo; } if (n == 1){ //若是n = 1 return preOne; } int i; for (i = 2; i <= n; i++){ //从第三个元素开始遍历 result = preOne + preTwo; //两数之和 preOne = preTwo; //第一个元素变为前一次相加的第二个元素 preTwo = result; //将结果赋值给第二个元素 } int j = i - 1; System.out.println("这是菲波那切数列的第"+j+"项:"+result); return result; } public static void checkInt(int n){ if (n >= 39 || n < 0){ throw new ArithmeticException(); } } public static void main(String[] args){ System.out.print("请输入一个小于39的数字n:"); try { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); checkInt(m); feibonaqie(m); }catch (Exception e){ System.out.println("输入的数字超过最大限制:"+e.getMessage()); } } }