方法一:利用递归
package com;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入n");
int n = sc.nextInt();
System.out.println(n+"的阶乘为:"+f(n));
}
public static int f(int n){
if(n==0||n==1)
return 1;
else
return n*f(n-1);
}
}
方法二:利用循环
package com;
import java.util.Scanner;
public class C2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入n");
int n =sc.nextInt();
System.out.println(n+"阶乘为:"+f(n));
}
public static int f (int n){
int s = 1;
for(int i=1;i<=n;i++){
s*=i;
}
return s;
}
}
能用循环的时候,采用循环比较简单。