首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

java 递归。小弟我如何算都得不出这个结果

2013-04-21 
java 递归。我怎么算都得不出这个结果public static void main(String []args){int x 5System.out.printl

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!  

热点排行