zoukankan      html  css  js  c++  java
  • Java递归调用

    6.递归调用

    方法的递归调用就是方法自身调用自身。

    以下程序因为递归没有结束的条件,所以一直压栈,没有弹栈,导致栈内存溢出错误!所以递归必须要有结束条件。

    public class RecursionTest01{

           //入口

           public static void main(String[] args){

                  m1();

           }

           public static void m1(){

                  m1(); //java.lang.StackOverflowError

           }

    }

    【例题1】:不使用递归,计算1-N的求和。

    public class RecursionTest02{

           public static void main(String[] args){

                  int n = 5;

                  //调用该方法完成1-N的求和

                  int retValue = method1(n);

                  System.out.println(retValue); //15

           }

           //该方法完成1-N的求和.

           public static int method1(int n){

                  int sum = 0;

                  for(int i=0;i<=n;i++){

                         sum += i;

                  }

                  return sum;

           }

    }

    【例题2】:使用递归,计算1-N的求和。

    public class RecursionTest03{

           public static void main(String[] args){

                  int n = 5;

                  //调用该方法完成1-N的求和

                  int retValue = method1(n);

                  System.out.println(retValue); //15

           }

          

           //该方法完成1-N的求和.

           //1+2+3+4+5+...N

           public static int method1(int n){

                  if(n==1){

                         return 1;

                  }else{

                         return n + method1(n-1); }}}

    【练习】:计算N的阶乘。两种方式:使用递归和不使用递归。

    public class RecursionTest04{

           public static void main(String[] rgs){

                  System.out.println(method1(5)); //120

           }

           public static int method1(int n){

               //不使用递归

                  int result = 1;

                  for(int i=1;i<=n;i++){

                         result *= i;

                  }

                  return result;

               //使用递归

                  if(n==1){

                         return 1;

                  }else{

                         return n * method1(n-1); }

           }

    }

     

  • 相关阅读:
    关于异步取消线程以及异步销毁锁的探讨
    pthread_mutex_init & 互斥锁pthread_mutex_t的使用(转)
    Qt设置全局的widget的stylesheet
    浅析pthread_cond_wait(转)
    575 Skew Binary
    HDU 1229 还是A+B
    10370
    10300
    UVA 10071 Problem B Back to High School Physics
    UVA 10055 Problem A Hashmat the brave warrior
  • 原文地址:https://www.cnblogs.com/superjishere/p/11780481.html
Copyright © 2011-2022 走看看