java打印1到10的阶乘
时间: 2024-05-14 13:14:13 浏览: 9
以下是Java程序,用于打印1到10的阶乘:
```java
public class Factorial {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
int factorial = 1;
for (int j = 1; j <= i; j++) {
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
}
}
```
输出结果:
```
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
```
相关问题
java直接打印一的阶乘到十的阶乘
以下是 Java 直接打印一到十的阶乘的代码:
```java
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
int factorial = 1;
for (int j = 1; j <= i; j++) {
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
}
}
```
输出结果为:
```
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
```
Java用递归求10的阶乘
以下是Java使用递归求10的阶乘的示例代码:
```
public class Main {
public static void main(String[] args) {
int n = 10;
int result = factorial(n);
System.out.println("10的阶乘为:" + result);
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
```
在上面的示例中,我们定义了一个名为factorial()的递归函数,该函数用于计算n的阶乘。如果n为0,则返回1。否则,递归调用factorial()函数来计算n-1的阶乘,并将结果乘以n。这个过程一直持续到n=0时,然后返回1,最终计算出n的阶乘。
在main()方法中,我们调用factorial()函数来计算10的阶乘,并将结果存储在result变量中。最后,我们将结果打印到控制台上。
运行上面的示例代码,将会输出以下结果:
```
10的阶乘为:3628800
```
这与前面使用for循环计算10的阶乘得到的结果相同。需要注意的是,在使用递归时,必须确保递归调用能够终止,否则可能会导致无限递归和栈溢出等问题。因此,在编写递归代码时,必须使用适当的终止条件来确保递归调用不会无限进行。