java例题_22 用递归求阶乘 5!

 1 /*22 【程序 22 递归求阶乘】 
 2 题目:利用递归方法求 5!。 
 3 程序分析:递归公式:fn!=fn*4! 
 4 */
 5 
 6 /*分析
 7  * 递归:如果其中每一步都要用到前一步或前几步的结果,称为递归的
 8  * 根据提示,可以用算法x!=x*(x-1)!;y=x-1,y!=y*(y-1)!;...
 9  * 
10  * */
11 
12 
13 package homework;
14 
15 public class _22 {
16 
17     public static void main(String[] args) {
18         // TODO Auto-generated method stub
19         int x=5;
20         System.out.println(JieCheng(x));
21     }
22     
23     public static int JieCheng(int x) {   //必须用int类型,否者不能返回int
24         if(x==1) {
25             return 1;             //限定递归的范围
26         }
27         else {
28             return x*(JieCheng(x-1));
29         }
30     }
31 
32 }

猜你喜欢

转载自www.cnblogs.com/scwyqin/p/12307187.html