返回列表 發帖

405-遞迴函數

  1. import java.util.Scanner;
  2. public class JPA04 {
  3.     static Scanner keyboard = new Scanner(System.in);
  4.     public static void main(String args[]) {
  5.         
  6.       ...
  7.     }
  8.    
  9.     ...

  10. }
複製代碼
Stay hungry,
Stay foolish.

  1. package hi87;

  2. import java.util.Scanner;

  3. public class hi788 {
  4.     static Scanner keyboard = new Scanner(System.in);
  5.     public static void main(String args[]) {
  6.         
  7.                
  8.      System.out.print("Input m:");
  9.      int m=keyboard.nextInt();
  10.      System.out.print(f(m));
  11.      }          

  12.    
  13.    
  14.     static int f(int m)
  15.     {
  16.            
  17.             if(m==1)
  18.             {
  19.                     return 2;
  20.             }
  21.             else
  22.             {
  23.                     return f(m-1)+2*m;
  24.             }
  25.     }
  26. }
複製代碼

TOP

  1. package text;
  2. import java.util.Scanner;
  3. public class JPA04 {
  4.     static Scanner keyboard = new Scanner(System.in);
  5.     public static void main(String args[]) {
  6.         
  7.       System.out.print("Input the number n: ");
  8.       int num=keyboard.nextInt();
  9.       System.out.println("Ans: "+f(num));
  10.     }
  11.    
  12.     static int f(int n)
  13.     {
  14.             if(n==1)
  15.             {
  16.                     return 2;
  17.             }
  18.             else
  19.                     return f(n-1)+2*n;
  20.     }
  21.    

  22. }
複製代碼

TOP

  1. package wwe;

  2. import java.util.Scanner;

  3. public class JPA04 {
  4.         static Scanner k = new Scanner(System.in);
  5.         public static void main(String[] args) {
  6.                 // TODO 自動產生的方法 Stub
  7.                
  8.                 System.out.println("Input the number  n: ");
  9.                 int n=k.nextInt();
  10.                 System.out.println("Ans:"+s(n));
  11.         }
  12.         static int s(int n)
  13.         {
  14.                 if(n==1)
  15.                 {
  16.                         return 2;
  17.                 }
  18.                 else
  19.                 {
  20.                         return s(n-1)+2*n;
  21.                 }
  22.         }

  23.        
  24.        
  25. }
複製代碼

TOP

返回列表