递归的打印和阶乘运用

 1 public class Recursion01{
 2     public static void main(String[] args){
 3             T t1 = new T();
 4             t1.test(4);//输出什么? n=2 n=3 n=4
 5             int res = t1.factorial(5);
 6             System.out.println("5 的阶乘 res =" + res);
 7 
 8 
 9     }
10 }
11 
12 class T{
13     //分析
14     public void test(int n){
15         if(n > 2){
16             test(n-1);
17         }
18         System.out.println("n =" + n);
19     }
20     //factorial 阶乘
21     public int factorial(int n){
22         if(n == 1){
23             return 1;
24         }else{
25             return factorial(n-1) * n;
26         } 
27     }
28 }

 

posted @ 2024-08-11 09:19  勤奋的小番茄  阅读(2)  评论(0编辑  收藏  举报