分别用+while+循环,+do+while+循环以及+for+实现一到二十的阶乘
时间: 2023-11-11 07:03:10 浏览: 79
1.使用while循环实现一到二十的阶乘的代码如下:
```
int i = 1;
int result = 1;
while(i <= 20){
int j = 1;
int factorial = 1;
while(j <= i){
factorial *= j;
j++;
}
result += factorial;
i++;
}
System.out.println(result);
```
2.使用do-while循环实现一到二十的阶乘的代码如下:
```
int i = 1;
int result = 1;
do{
int j = 1;
int factorial = 1;
do{
factorial *= j;
j++;
}while(j <= i);
result += factorial;
i++;
}while(i <= 20);
System.out.println(result);
```
3.使用for循环实现一到二十的阶乘的代码如下:
```
int result = 1;
for(int i = 1; i <= 20; i++){
int factorial = 1;
for(int j = 1; j <= i; j++){
factorial *= j;
}
result += factorial;
}
System.out.println(result);
```
阅读全文