第一句的System.out.println(x+" to the power 4 is "+power(x,4)); 就是调用静态方法power(x,4),只是输出的时候你前面多了个x+,double x=5.0加上一串字符串" to the power 4 is "变成另外一个字符串"5.0 to the power 4 is " ,跟你要调用的静态方法没有关系。
程序执行过程System.out.println(x+" to the power 4 is "+power(x,4)); power(x,4)=x*power(x,3)power(x,3)=x*power(x,2)power(x,2)=x*power(x,1)power(x,1)因为1不大于1 所以执行 最后一个else n==0 ? 1.0:x; 当n=0时返回1否则返回x 明显返回x 然后程序往上执行 得到结果最后得到结果625 呵呵 个人理解
3==n 竟然 n>1的那个判断..................................................一直到1==n 返回了1
返回了1这个就到最后了,于是原路返回 所有的值全部求出
自己慢慢想想。
就是调用静态方法power(x,4),只是输出的时候你前面多了个x+,double x=5.0加上一串字符串" to the power 4 is "变成另外一个字符串"5.0 to the power 4 is " ,跟你要调用的静态方法没有关系。
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;
}
}
加了注释,你自己运行看看吧。
4==n 进入 n>1的那个判断 返回5*power(5*3) 红色部分等于又掉用本身的方法 也就是3==n
3==n 竟然 n>1的那个判断............................................. ..... 一直到1==n 返回了1
返回了1这个就到最后了,于是原路返回 所有的值全部求出 2楼说的这个是不是当返回1时进入:
if(n>1)
return x*power(x,n-1);
.......
else
return n==0 ? 1.0:x;
结果返回x,也就是5.0
到这里我都明白,但是往后怎么会返回去的我就不台明白了