递归求斐波那契数据列

 1 import java.util.Scanner;
 2 
 3 /*
 4 斐波那契数列:1,1,2,3,5,8,13,21,34......
 5 可以看出从第三项开始每一项都是前两项之和
 6  */
 7 public class Fibonacci {
 8     public static void main(String[] args) {
 9         Scanner sc=new Scanner(System.in);
10         System.out.println("输入一个正整数x:");
11         int x=sc.nextInt();
12         System.out.println(fun(x));
13     }
14     public static int fun(int x){
15         if(x==1||x==2){
16             return 1;
17         }else
18         {
19             return fun(x-1)+fun(x-2);
20         }
21     }
22 }

结果显示:

 1 输入一个正整数x:

2 23

3 28657 

猜你喜欢

转载自www.cnblogs.com/zhang-sw/p/12813597.html
今日推荐