递归

递归

自己调用自己,

递归结构包括两部分:

  • 递归头:什么时候不能调用自身方法,如果没有头,将陷入死循环
  • 递归体:什么时候需要调用自身方法
package big.com.Cai; public class Annotation {     public static void main(String[] args) {         System.out.println(func(5));     }     public static int func(int n){         if(n==1){             return 1;         }         else             return n*func(n-1);         //f(1) 1         //f(2) 2*f(1)         //f(3) 3*f(2)         //f(4) 4*f(3)     } } 

java都是使用栈机制

简易计算器:

package big.com.Cai;  import java.util.Scanner;  public class Annotation {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println(请输入两位待计算的数:);         double num1 = s.nextDouble();         double num2 = s.nextDouble();         System.out.println(请输入想进行的算法:);         String c = s.next();         switch(c){             case +:                 System.out.println(num1+++num2+=+Cal1(num1,num2));                 break;             case -:                 System.out.println(num1+-+num2+=+Cal2(num1,num2));                 break;             case *:                 System.out.println(num1+*+num2+=+Cal3(num1,num2));                 break;             case /:                 System.out.println(num1+/+num2+=+Cal4(num1,num2));                 break;         }     }     public static double Cal1(double num1,double num2){         return num1+num2;     }     public static double Cal2(double num1,double num2){         return num1-num2;     }     public static double Cal3(double num1,double num2){         return num1*num2;     }     public static double Cal4(double num1,double num2){         return num1/num2;     } }