用递归写一个简单的计算阶乘的方法


 1 public class Factorial {
 2 
 3     public static void main(String[] args) {
 4         // 测试一下计算9的阶乘
 5         int n = 9;
 6         int result = factorial(n);
 7         System.out.println(n + "的阶乘为:" + result);
 8     }
 9 
10     // 计算阶乘的方法
11     public static int factorial(int n) {
12         if (n == 1) {// 递归头(何时结束递归)
13             return 1;
14         } else {// 递归体(何时调用方法自己本身)
15             return n * factorial(n - 1);
16         }
17     }
18 
19 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM