利用遞歸和循環求階乘


求一個數的階乘

 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