用C语言while、do-while、for三种不同的循环方法编程求1!+2!+3!+…+20!的值;
时间: 2024-01-16 14:05:00 浏览: 73
可以使用while、do-while和for三种循环方法来编程求1!+2!+3!+…+20!的值。下面是使用这三种循环方法的示例代码:
1. 使用while循环:
```c
#include <stdio.h>
int main() {
int n = 1;
int factorial = 1;
int sum = 0;
while (n <= 20) {
factorial *= n;
sum += factorial;
n++;
}
printf("1!+2!+3!+...+20! = %d\n", sum);
return 0;}
```
2. 使用do-while循环:
```c
#include <stdio.h>
int main() {
int n = 1;
int factorial = 1;
int sum = 0;
do {
factorial *= n;
sum += factorial;
n++;
} while (n <= 20);
printf("1!+2!+3!+...+20! = %d\n", sum);
return 0;
}
```
3. 使用for循环:
```c
#include <stdio.h>
int main() {
int factorial = 1;
int sum = 0;
for (int n = 1; n <= 20; n++) {
factorial *= n;
sum += factorial;
}
printf("1!+2!+3!+...+20! = %d\n", sum);
return 0;
}
```
这三种循环方法都可以得到相同的结果,即1!+2!+3!+…+20!的值。
阅读全文