编写程序。分别用while语句、do-while语句和for语句编写一个求阶乘n!的java程序。
时间: 2023-04-20 16:04:30 浏览: 154
Java实验-循环语句,for,while,do-while
5星 · 资源好评率100%
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);
}
}
```
阅读全文