java入门学习(十七) 递归

来源:互联网 发布:网络id 编辑:程序博客网 时间:2024/06/06 17:26

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

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

迄今为止你所看到的这些方法都可以调用其他的方法,然而一个方法也可以调用它自己,我们把这种调用称作递归(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

0 0
原创粉丝点击