在Java中计算阶乘可以使用递归或循环的方式实现。以下是两种方法的代码示例: 1. 使用循环计算阶乘 ```java public class Factorial { public static long factorial(int n) { if (n < 0) { throw new IllegalArgumentException("阶乘数不能为负数"); } long result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } public static void main(String[] args) { int number = 9; System.out.println(number + "的阶乘是: " + factorial(number)); } } ``` 2. 使用递归计算阶乘 ```java public class Factorial { public static long factorial(int n) { if (n < 0) { throw new IllegalArgumentException("阶乘数不能为负数"); } if (n == 0 || n == 1) { return 1; } return n * factorial(n - 1); } public static void main(String[] args) { int number = 9; System.out.println(number + "的阶乘是: " + factorial(number)); } } ``` 注意事项: 1. 当n较大时(如n>20),阶乘结果会超过long类型的最大值,可以考虑使用BigInteger类来处理大数阶乘。 2. 递归方法虽然简洁,但对于大数阶乘可能导致栈溢出,循环方法更安全。 3. 输入验证很重要,负数没有阶乘定义,应该抛出异常或返回特殊值。 [2025-03-26 23:54:47 | AI写代码神器 | 346点数解答]