Java遞迴實現階乘
阿新 • • 發佈:2021-01-27
技術標籤:java基礎
Java遞迴實現階乘
package com.ycy1;
public class Test05 {
public static void main(String[] args) {
int i = 5;
int fac = Test05.fac(i);
System.out.println(i + " 的階乘是:" + fac);
}
public static int fac(int i) {
int result = 0;
if (i >= 0) {
if (i == 0 || i == 1) {
result = 1;
} else {
result = i * fac(i - 1);
}
} else {
System.out.println("資料有誤!");
result = -1;
}
return result;
}
}