C语言编写程序求1!+2!+….n!
时间: 2023-08-04 20:05:54 浏览: 89
您好!您可以使用C语言编写一个函数来计算1!+2!+....+n!,具体实现可以参考以下代码:
```c
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n, sum = 0;
printf("请输入n的值:");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
printf("1!+2!+...+%d!的值为:%d\n", n, sum);
return 0;
}
```
这段代码中,factorial函数用来计算n的阶乘,主函数中使用for循环来计算1!+2!+....+n!的值,并输出结果。
相关问题
用C语言编写程序求1!+2!+....+10!
以下是用C语言编写程序求1!+2!+....+10!的代码:
```c
#include <stdio.h>
int main() {
int i, j;
double sum = 0, fac = 1;
for (i = 1; i <= 10; i++) {
fac *= i;
sum += fac;
}
printf("1!+2!+....+10!=%.0f\n", sum);
return 0;
}
```
编写程序求1!+2!+3!+..+n!
以下是C语言编写程序求1!+2!+3!+..+n!的例子:
```c
#include <stdio.h>
int main()
{
int n, i, j, sum = 0, s = 1;
scanf("%d", &n); // 输入n
for (i = 1; i <= n; i++) {
s = 1; // 每次循环前将s初始化为1
for (j = 1; j <= i; j++) {
s = s * j; // 计算i的阶乘
}
sum = sum + s; // 累加阶乘之和
}
printf("%d", sum); // 输出结果
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)