Java-方法的使用习题-1、递归求 N 的阶乘2、递归求 1 + 2 + 3 + ... + 10。3、按顺序打印一个数字的每一位(例如 1234 打印出 1 2 3 4) (递归)

1、递归求 N 的阶乘

package gyy;
import java.util.Scanner;
public class yinger{
    
    
 public static void main(String[] args) {
    
    
  Scanner sc=new Scanner(System.in);
  int N=sc.nextInt();
  System.out.print(N+"!="+Factorial(N));
  sc.close();
 }
 public static int Factorial(int n) {
    
    
  if(n==1) {
    
    
   return 1;
  }else {
    
    
   return n*Factorial(n-1);
  }
 }
}

运行结果:

5
5!=120

2、递归求 1 + 2 + 3 + … + 10

package gyy;
import java.util.Scanner;
public class yinger{
    
    
 public static void main(String[] args) {
    
    
  Scanner sc=new Scanner(System.in);
  int N=sc.nextInt();
  System.out.print(Factorial(N));
  sc.close();
 }
 public static int Factorial(int n) {
    
    
  if(n>1){
    
    
   return n+Factorial(n-1);
  }else {
    
    
   return n;
  }
 }
} 

y运行结果:

10
55

3、按顺序打印一个数字的每一位(例如 1234 打印出 1 2 3 4) (递归)

package gyy;
import java.util.Scanner;
public class yinger{
    
    
 public static void main(String[] agrs) {
    
    
  System.out.print("请输入一个数字:");
  Scanner s=new Scanner(System.in);
  int integer=s.nextInt();
  //调用拆分一个整数的方法
  splitInteger(integer);
  s.close();
 }
 public static int splitInteger(int integer) {
    
    
  if(integer>9) {
    
    
  splitInteger(integer/10);
  }
  System.out.print(integer%10+" ");
  return 0;
 }
}

运行结果:

请输入一个数字:1234
1 2 3 4 

猜你喜欢

转载自blog.csdn.net/weixin_44378053/article/details/104214494