java 递归。我怎么算都得不出这个结果

u010291093 2013-04-19 02:42:15
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
...全文
321 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
qiuqiang520 2013-04-19
  • 打赏
  • 举报
回复
补充,最后一个不是1,power(x,1),n=1,里面没有n==1的情况,属于最后的else,power(5,1)=5,所以应该是5*5*5*5才对!
qiuqiang520 2013-04-19
  • 打赏
  • 举报
回复
power(x,4))=5*power(x,3))=5*5*power(x,2))=5*5*5*power(x,1))=5*5*5*5=625!
陈志凯 2013-04-19
  • 打赏
  • 举报
回复
调试模式,单步执行,一切就清楚了,有耐性的话
u010291093 2013-04-19
  • 打赏
  • 举报
回复
引用 2 楼 malligator 的回复:
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 是整除
你好,能不能再写详细点,我知道这样已经很详细了,可是过程不是很清楚,能否再详细点,讲下过程,5*5*5*5*1 为什么最后一个是1??
malligator 2013-04-19
  • 打赏
  • 举报
回复
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 是整除
七神之光 2013-04-19
  • 打赏
  • 举报
回复
(x*power(x,n-1) 这里有递归 5*5*5*5*1

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧