代码如下:
package cn.question.test;
public class FactorialTest {
/**
* @param args
*/
public static void main(String[] args) {
doFactorial(5);
System.out.println("------------------------");
long a = 0;
a = doFactorila2(5);
System.out.println("a="+a);
}
//遍历循环
public static long doFactorial(long n){
long factors = 1;
if(n<0){
System.out.println("输入数字不符合规范");
}
else if(n == 0 || n == 1){
return 1;
}
else{
for(int i =1;i<n;i++){
factors = factors * i;
}
System.out.println("factors="+factors);
}
return factors;
}
//递归方法
public static long doFactorila2(long n){
//long factors = 1;
long factors = 0;
if(n<0){
System.out.println("输入数字不符合规范");
}
else if(n != 0){
return factors = n* doFactorila2(n-1);
}
System.out.println("factors输出结果为"+factors);
return factors;
}
}
结果为:
factors=24
------------------------
factors输出结果为0
a=0
为什么我第二个递归方法输出的结果为零呢,它跟第一个递归方法传入的参数一样!我的递归也应该没问题啊!
|
|