java使用while、do...while和for循环三种结构计算用户输入的正整数的阶乘
时间: 2024-12-18 10:16:39 浏览: 9
在Java中,可以使用while、do...while和for循环来计算用户输入的正整数的阶乘。以下是三种结构的示例:
1. **while循环**:
```java
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个正整数:");
int num = input.nextInt();
int factorial = 1;
while (num > 0) {
factorial *= num;
num--;
}
System.out.printf("该数字的阶乘是:%d", factorial);
}
}
```
2. **do...while循环**:
```java
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = 0; // Initialize with a default value to avoid infinite loop on first iteration
do {
System.out.print("请输入一个正整数:");
num = input.nextInt();
if (num < 0) {
System.out.println("输入错误,请输入正整数。");
continue;
}
int factorial = 1;
while (num > 0) {
factorial *= num;
num--;
}
} while (num <= 0); // Ensure the loop continues until a positive number is entered
System.out.printf("该数字的阶乘是:%d", factorial);
}
}
```
3. **for循环**:
```java
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个正整数:");
int num = input.nextInt();
if (num < 0) {
System.out.println("输入错误,请输入正整数。");
} else {
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.printf("该数字的阶乘是:%d", factorial);
}
}
}
```
阅读全文