用示例解释Java中的递归
就像C和C++编程语言一样,java也支持递归。递归是一个函数递归调用的过程。
就Java编程而言,递归是允许方法调用自身的过程。
考虑示例:
在此示例中,我们正在计算给定数字的阶乘。假设有一个数字5,则其阶乘将为1x2x3x4x5=120。并且阶乘将通过递归函数进行计算。
class Factorial
{
//递归方法
int fact(int num)
{
int result;
//如果/当num为1-
if(num==1)
return 1;
//调用方法本身
result = fact(num-1) * num;
return result;
}
}
public class ExampleRecursion
{
public static void main(String args[])
{
Factorial factMethod = new Factorial();
System.out.println("Factorial of 1 is: " + factMethod.fact(1));
System.out.println("Factorial of 2 is: " + factMethod.fact(2));
System.out.println("Factorial of 3 is: " + factMethod.fact(3));
System.out.println("Factorial of 4 is: " + factMethod.fact(4));
System.out.println("Factorial of 5 is: " + factMethod.fact(5));
}
}输出结果
Factorial of 1 is: 1 Factorial of 2 is: 2 Factorial of 3 is: 6 Factorial of 4 is: 24 Factorial of 5 is: 120
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短