分别用for、while和do-while循环语句以及递归方法计算n!,并输出算式
时间: 2024-02-15 15:02:20 浏览: 111
好的,以下是四种方式计算n!的代码(假设n为正整数):
1. for循环:
```java
int factorial = 1;
for(int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println(n + "! = " + factorial);
```
2. while循环:
```java
int factorial = 1;
int i = 1;
while(i <= n) {
factorial *= i;
i++;
}
System.out.println(n + "! = " + factorial);
```
3. do-while循环:
```java
int factorial = 1;
int i = 1;
do {
factorial *= i;
i++;
} while(i <= n);
System.out.println(n + "! = " + factorial);
```
4. 递归方法:
```java
public static int factorial(int n) {
if(n == 1) {
System.out.print(n);
return 1;
} else {
System.out.print(n + " * ");
return n * factorial(n-1);
}
}
// 调用方法
int result = factorial(n);
System.out.println(" = " + result);
```
注意:递归方法输出的算式与前三种方式不同,因为递归方法是从n开始往下递归,所以输出的算式是从n开始往上的。
阅读全文