阶乘是一个数学概念,表示从1到给定正整数n的所有整数的乘积。在Java中,可以使用递归或循环来计算阶乘。
以下是使用循环计算阶乘的Java代码示例:
public class Factorial {
public static void main(String[] args) {
int n = 5; // 要计算阶乘的正整数
int result = factorial(n);
System.out.println("阶乘结果为:" + result);
}
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
上述代码定义了一个名为factorial
的方法,该方法接受一个正整数参数n
,并返回其阶乘的结果。在main
方法中,我们调用了factorial
方法来计算阶乘,并将结果打印输出。