求1+2!+3!+……+n!,n由键盘输入 用双层循环
时间: 2023-11-17 21:00:49 浏览: 176
以下是用双层循环求1+2!+3!+……+n!的代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, j, sum = 0, fac = 1;
printf("请输入一个正整数n:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
fac = 1;
for (j = 1; j <= i; j++) {
fac *= j;
}
sum += fac;
}
printf("1+2!+3!+...+n!的值为:%d\n", sum);
system("pause");
return 0;
}
```
相关问题
用C语言计算:1!+2!+3+……+n!(用双层循环完成)
以下是用C语言计算1!+2!+3+……+n!(用双层循环完成)的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
int fun(int x) {
int Sn = 0;
int S;
for (int i = 1; i <= x; ++i) {
S = 1;
for (int j = 1; j <= i; ++j) {
S *= j;
}
Sn += S;
}
return Sn;
}
int main() {
int n;
printf("您需要1到多少的阶乘之和,请输入(此值请小于26)\n");
scanf("%d", &n);
printf("数字1到数字%d各阶乘之和为%d\n", n, fun(n));
system("pause");
return 0;
}
```
c语言求s=1!+ 2!+ 3!+ ...+10!,并输出(请分别用双层循环和单层循环解决)
C语言求s=1!+ 2!+ 3!+ ...+10!的问题可以使用双层循环和单层循环两种方式解决。
1. 双层循环解决:
```c
#include <stdio.h>
int main() {
int i, j;
int factorial, sum = 0;
for (i = 1; i <= 10; i++) {
factorial = 1;
for (j = 1; j <= i; j++) {
factorial *= j;
}
sum += factorial;
}
printf("双层循环解决,s的值为:%d\n", sum);
return 0;
}
```
2. 单层循环解决:
```c
#include <stdio.h>
int main() {
int i;
int factorial = 1, sum = 0;
for (i = 1; i <= 10; i++) {
factorial *= i;
sum += factorial;
}
printf("单层循环解决,s的值为:%d\n", sum);
return 0;
}
```