public class Text10 {
public static void main(String[] args) {
AAA a = new AAA(); //new一个新的对象
int res = a.He(4); //用res来接受AAA类中He方法的返回值sum
System.out.print(res); //输出res
}
}
class AAA { //新创建了一个类AAA
public int factorial(int n) { //创建了一个方法名为factorial,并且有返回值,这个方法是计算n的阶乘的值
if (n == 1) { //阶乘的原理为:1的阶乘为1,(n>1)n!=1*2*3*....*n
return 1;
} else { //这里用递归的方法进行书写
return factorial(n - 1) * n;
}
}
public int He(int n) { //新创建一个方法名为He,并且有返回值,这个方法是计算阶乘的和
AAA A = new AAA(); //new一个新的对象,这里要用到AAA类中方法factorial的阶乘值
int sum = 0; //创建一个 int类型的um;用来接收接收阶乘的和
for (int i = 1; i <= n; i++) { //利用for循环使每次的阶乘相加
sum += A.factorial(i);
}
return sum; //返回sum的值
}
}
这里是结果展示图