Java中的递归阶乘方法
任何非负整数的阶乘基本上都是小于或等于该整数的所有整数的乘积。阶乘可以使用递归方法获得。
演示此过程的程序如下:
示例
public class Demo {
public static long fact(long n) {
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
public static void main(String args[]) {
System.out.println("The factorial of 6 is: " + fact(6));
System.out.println("The factorial of 0 is: " + fact(0));
}
}输出结果
The factorial of 6 is: 720 The factorial of 0 is: 1
现在让我们了解上面的程序。
该方法fact()计算数字n的阶乘。如果n小于或等于1,则返回1。否则,它将递归调用自身并返回n*fact(n-1)。演示此代码段如下:
public static long fact(long n) {
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}在中main(),fact()使用不同的值调用该方法。演示此代码段如下:
public static void main(String args[]) {
System.out.println("The factorial of 6 is: " + fact(6));
System.out.println("The factorial of 0 is: " + fact(0));
}热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬