编写程序。分别用while语句、do-while语句和for语句编写一个求阶乘n!的java程序。
时间: 2023-04-20 07:04:30 浏览: 157
阶乘计算 编写程序,对给定的n(n≦100),
4星 · 用户满意度95%
while语句:
```
import java.util.Scanner;
public class FactorialWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个正整数:");
int n = input.nextInt();
int result = 1;
int i = 1;
while (i <= n) {
result *= i;
i++;
}
System.out.println(n + "! = " + result);
}
}
```
do-while语句:
```
import java.util.Scanner;
public class FactorialDoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个正整数:");
int n = input.nextInt();
int result = 1;
int i = 1;
do {
result *= i;
i++;
} while (i <= n);
System.out.println(n + "! = " + result);
}
}
```
for语句:
```
import java.util.Scanner;
public class FactorialFor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个正整数:");
int n = input.nextInt();
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println(n + "! = " + result);
}
}
```
阅读全文