求1!+2!+3!的和c语言程序
时间: 2023-08-29 10:09:01 浏览: 66
以下是求 1!+2!+3! 的 C 语言代码:
```c
#include <stdio.h>
// 计算 n 的阶乘
int factorial(int n) {
int i, f = 1;
for (i = 1; i <= n; i++) {
f *= i;
}
return f;
}
int main() {
int sum = 0;
sum += factorial(1);
sum += factorial(2);
sum += factorial(3);
printf("1!+2!+3! = %d\n", sum);
return 0;
}
```
运行结果为:
```
1!+2!+3! = 9
```
相关问题
while求1!+2!+20!c语言
以下是使用while循环求1!+2!+...+20!的C语言程序:
```c
#include <stdio.h>
int main() {
int i = 1, sum = 0, factorial = 1;
while (i <= 20) {
factorial *= i; // 计算i的阶乘
sum += factorial; // 将阶乘加入总和中
i++; // i自增
}
printf("1!+2!+...+20!=%d\n", sum); // 输出结果
return 0;
}
```
c语言编程求1!+2!+3!+……+n!
以下是C语言编程求1!+2!+3!+……+n!的函数fun以及在main函数中调用fun函数并输出结果的代码:
```c
#include <stdio.h>
int fun(int n) {
int i, j, sum = 0, temp = 1;
for (i = 1; i <= n; i++) {
temp = 1;
for (j = 1; j <= i; j++) {
temp *= j;
}
sum += temp;
}
return sum;
}
int main() {
int n, result;
printf("请输入n的值:");
scanf("%d", &n);
result = fun(n);
printf("%d的阶乘和为:%d\n", n, result);
return 0;
}
```
输入n的值后,程序会调用fun函数计算1!+2!+3!+……+n!的和,并输出结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)