java入门学习(十七) 递归

我的网站 分享装修案例的网站仙美仙网

递归 说白了 就是自己调用自己 一直到不符合条件 跳出方法体

迄今为止你所看到的这些方法都可以调用其他的方法,然而一个方法也可以调用它自己,我们把这种调用称作递归(recursion).很明显。你一定要在递归方法中包括一些逻辑判断,这样才能够在最后停止调用它自己。我们将用一个简单的例子来介绍它的实现过程。 我们可以编写一个方法来计算一个变量的整数幂,也就是计算x的n次方或者x*x*…*x,即x乘以它自身n次。我们可以应用这样一个算式得到结果,即x的n次方等于x的(n-1)次方乘以x.



这里有一个包含递归方法power()的完整程序:


public class PowerCalc
{
  public static void main(string [] arga)
   {
     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));
)
  //Raise x to the power n
  static double power(double x,int n)
  {
   it(n>1)
     return x*power(x,n=1);          //Recersive call
   else if (n<0)
     return 1.0/power(x,n);         //Negative Dower of x
   else
     return n==0 ? 1.0 :x;          //when n is  return 1. otherwise x
 }
}
    这个程序将产生的输出结果为:
    5.0 to the power 4 is 625.0
    7.5 to the power 5 is 23730.46875
    7.5 to the power 0is 1.0
    10  to the power -2 is 0.01

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值