用 do…..while, while, for 三种循环语句求 n!(要求 n 的值从键盘输入), 输出结果。
时间: 2024-06-13 20:07:35 浏览: 92
练习使用for、while、do while、foreach in等循环语句
以下是三种循环语句求n!的例子,其中n的值从键盘输入:
1.使用do...while循环语句
```java
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int result = 1; int i = 1;
do {
result *= i;
i++;
} while (i <= n);
System.out.println(n + "! = " + result);
}
}
```
2.使用while循环语句
```java
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int result = 1; int i = 1;
while (i <= n) {
result *= i;
i++;
}
System.out.println(n + "! = " + result);
}
}
```
3.使用for循环语句
```java
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int result = 1; for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println(n + "! = " + result);
}
}
```
阅读全文