java语言,输入整数n(n>=0),分别利用for循环、while循环、do…while循环求n!,并调试运行成功
时间: 2024-05-14 10:12:09 浏览: 49
用java语言写的实现输入整数
3星 · 编辑精心推荐
for循环实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println(n + "! = " + result);
}
}
```
while循环实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.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 Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int result = 1;
int i = 1;
do {
result *= i;
i++;
} while (i <= n);
System.out.println(n + "! = " + result);
}
}
```
阅读全文