n的阶乘表示:n=1 x 2 x 3 ....(n-2) x (n-1) x n
举例:9的阶乘等于1x2x3x4x5x6x7x8x9
阶乘也可以使用递归方式表示为: 0! = 1, n! = (n-1)! x n (n的阶乘等于n-1的阶乘 x n)
具体代码如下:
方法一:使用循环的方式
//求n的阶乘
public class Demo3 {
public static void main(String[] args) {
// 方法一:
System.out.println("="+factorial(5));
}
// 循环
public static int factorial(int n) {
// 用于记录阶乘结果,必须为1,乘积不变
int result = 1;
// 循环n次相乘
for (int i = 1; i <= n; i++) {
result *= i;
System.out.print(i+"*");
}
// 返回结果
return result;
};
}
方式二:使用递归的方式
//求n的阶乘
public class Demo3 {
public static void main(String[] args) {
// 方法二:
for (int i = -3; i<=30; i++){
System.out.println("变量为"+i+":"+factorial2(i));
}
}
// 递归
public static int factorial2(int n){
// 递归的回归条件
if(n==1){
return 1;
}
//有效数据校验
if(n==0){
return 0;
}
if(n<0){
return -1;
}
return n*factorial2(n-1);
}
}