Java递归
package funuction;
/**
* 计算机阶乘
* 公式:n != 1 x 2 x 3 x ... x n
*/
public class FactoriaDemo {
public static void main(String[] args) {
System.out.println(fact(3));
System.out.println(factRecur(3));
}
//定义 计算阶乘的方法(不使用递归)
public static int fact(int n) {
int result = 1;
//使用循环结构计算阶乘
for(int i = 2; i <= n; i ++) {
result *= i;
}
return result;
}
//定义 计算阶乘的方法(使用递归)
public static int factRecur(int n) {
if(n==1) return 1;
return n * factRecur(n -1);
}
}
阅读剩余
版权声明:
作者:tiantian
链接:https://blog.cv0.cn/92/
文章版权归作者所有,未经允许请勿转载。
THE END