利用递归和循环求阶乘


求一个数的阶乘

 1 //求一个数的阶乘
 2 public class Test_2 {
 3 
 4     public static int f1(int n) { // 递归
 5         if (n == 1 || n == 0)
 6             return 1;
 7         else
 8             return n * f1(n - 1);
 9     }
10 
11     public static void f2(int a) { // 循环
12         long sum = 1;
13         for (int i = 1; i <= a; i++) {
14 
15             sum *= i;
16 
17         }
18         System.out.println(sum);
19     }
20 
21     public static void main(String[] args) {
22         Scanner sc = new Scanner(System.in);
23         int a = sc.nextInt();
24         System.out.println(f1(a));
25         f2(a);
26     }
27 }

 


免责声明!

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



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