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

java 递归。我怎么算都得不出这个结果
public static void main(String []args)
{
int x =5;
System.out.println(x + " to the power 4 is " +power(x,4));
System.out.println("7 to the power 5 is " +power(7,5));
System.out.println(x + " to the power 0 is " +power(7,0));
System.out.println("10 to the power -2 is " +power(10,-2));
}
static int power(double x,int n)
{
if(n>1)
return (int) (x*power(x,n-1));
else if(n<0)
return  1/power(x,-n);
else
return (int) (n==0?1:x);
}



这个程序输出如下:
5 to the power 4 is 625 //625这个是怎么得出来的?请告诉我计算方法?这个递归我看不出来为什么会得出如此结果
7.5 to the power 5 is 16807
5 to the power 0 is 1
10 to the power -2 is 0

------解决方案--------------------
(x*power(x,n-1) 这里有递归  5*5*5*5*1
------解决方案--------------------
5 to the power 4 =5*5*5*5*1=625
7 to the power 5 =7*7*7*7*7*1=16807
5 to the power 0 = 1
10 to the power -2 =1/(10*10*1)=0  是整除


------解决方案--------------------
power(x,4))=5*power(x,3))=5*5*power(x,2))=5*5*5*power(x,1))=5*5*5*5=625!