日期:2014-05-20  浏览次数:20667 次

请教JAVA中递归函数的过程解释[在线等]
public class PowerCalc{
public static void main(String[] args){
double x=5.0;
System.out.println(x+" to the power 4 is "+power(x,4));
System.out.println("7.5 to the power 5 is"+power(7.5,5));
System.out.println("7.5 to the power 0 is"+power(7.5,0));
System.out.println("10 to the power -2 is"+power(10,-2));
}
static double power(double x, int n){
if(n>1)
return x*power(x,n-1);
else if(n<0)
return 1.0/power(x,-n);
else
return n==0 ? 1.0:x;
}
}
麻烦解释每一步的过程 辛苦了 谢谢!

------解决方案--------------------
4==n 进入 n>1的那个判断 返回5*power(5*3) 红色部分等于又掉用本身的方法 也就是3==n 
3==n 竟然 n>1的那个判断.............................................

.....

一直到1==n 返回了1 
返回了1这个就到最后了,于是原路返回 所有的值全部求出
------解决方案--------------------
Java code

static double power(double x, int n){ 
        if(n>1){
           System.out.println(" n is :"+n+"。call method power("+x+","+(n-1)+")。"+" return is  "+x+"*power("+x+","+(n-1)+")。");
           return x*power(x,n-1);
        }
        else if(n <0) 
           return 1.0/power(x,-n); 
        else {
            System.out.println(" the method end here。last method is power("+x+","+n+") ,return is :"+(n==0 ? 1.0:x));
           return n==0 ? 1.0:x;
        }
    }

------解决方案--------------------
你用dubug以下一步一步看看 就很好了
------解决方案--------------------
java程序员群 4247660 欢迎大家的加入
------解决方案--------------------
你把我加的注释执行下,应该能明白吧。。。