当前位置: 技术问答>java相关
请讲一讲使用递归方法算阶乘!谢谢!!有个例子不明白!!
来源: 互联网 发布时间:2017-04-03
本文导语: class Factorial { //this is a recursive method int fact(int n) { int result; if (n == 1) return 1; result = fact(n-1) * n; return result; } } class Recursion { public static void main(String arg[]) { Factorial f = new Fact...
class Factorial {
//this is a recursive method
int fact(int n) {
int result;
if (n == 1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String arg[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
//this is a recursive method
int fact(int n) {
int result;
if (n == 1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String arg[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
|
int fact(int n) {
int result;
if (n == 1) return 1; //n=1;函数返回值是1
result = fact(n-1) * n; //得到fact(n-1)的返回值并*n
return result;
}
fact(4) = fact(3)*4;
fact(3) = fact(2)*3;
fact(2) = fact(1)*2;
fact(1) = 1;
int result;
if (n == 1) return 1; //n=1;函数返回值是1
result = fact(n-1) * n; //得到fact(n-1)的返回值并*n
return result;
}
fact(4) = fact(3)*4;
fact(3) = fact(2)*3;
fact(2) = fact(1)*2;
fact(1) = 1;