Sn=1! + 2! + 3! + 4! + 5! + .... + n!
时间: 2023-11-24 22:51:51 浏览: 155
以下是两种方法来求Sn=1! + 2! + 3! + 4! + 5! + .... + n!的值:
1. Python代码:
```python
n = int(input("请输入n的值:"))
total = 0
for i in range(1, n+1):
factorial = 1
for j in range(1, i+1):
factorial *= j
total += factorial
print("Sn的值为:", total)
```
2. C语言代码:
```c
#include <stdio.h>
int main() {
long long n, i, j, factorial, total = 0;
printf("请输入n的值:");
scanf("%lld", &n);
for (i = 1; i <= n; ++i) {
factorial = 1;
for (j = 1; j <= i; ++j) {
factorial *= j;
}
total += factorial;
}
printf("Sn的值为:%lld", total);
return 0;
}
```
相关问题
c语言编写函数求 Sn=1!+2!+3!+4!+5!+...+n! 的值
以下是C语言编写函数求Sn=1!+2!+3!+4!+5!+...+n!的值的代码:
```c
#include <stdio.h>
int fun(int x) {
if (x == 0) return 1;
return x * fun(x - 1);
}
int main() {
int n, sum = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += fun(i);
}
printf("%d", sum);
return 0;
}
```
求 Sn=1!+2!+3!+4!+5!+…+n!
这是一个求阶乘和的问题,可以使用循环结构和递归结构来实现。
使用循环结构的代码如下:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int sum = 0;
int fac = 1;
for (int i = 1; i <= n; i++) {
fac *= i;
sum += fac;
}
cout << sum << endl;
return 0;
}
```
使用递归结构的代码如下:
```c++
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n;
cin >> n;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
cout << sum << endl;
return 0;
}
```
阅读全文