计算1/1!+1/2!…+n!的前n项和
时间: 2023-12-05 19:06:35 浏览: 211
以下是两种计算1/1!+1/2!…+n!的前n项和的方法:
1.使用for循环计算:
```python
n = int(input("请输入正整数n:"))
sum = 0
factorial = 1
for i in range(1, n+1):
factorial *= i
sum += 1/factorial
print("1/1!+1/2!+...+1/n!的前n项和为:%.2f" % sum)
```
2.使用while循环计算:
```python
n = int(input("请输入正整数n:"))
sum = 0
factorial = 1
i = 1
while i <= n:
factorial *= i
sum += 1/factorial
i += 1
print("1/1!+1/2!+...+1/n!的前n项和为:%.2f" % sum)
```
相关问题
c++实现1/1!+1/(1!+4!)+1/(1!+4!+7!)+1/(1!+4!+7!+10!)+1/(1!+4!+7!+10!+13!)+1/(1!+4!+7!+10!+13!+16!)+1/(1!+4!+7!+10!+13!+16!+19!)
以下是C++实现1/1!+1/(1!+4!)+1/(1!+4!+7!)+1/(1!+4!+7!+10!)+1/(1!+4!+7!+10!+13!)+1/(1!+4!+7!+10!+13!+16!)+1/(1!+4!+7!+10!+13!+16!+19!)的代码和注释:
```c++
#include <iostream>
using namespace std;
int main() {
int n = 7; // n为7,即求前7项的和
double sum = 0; // 初始化和为0
double factorial = 1; // 阶乘的初始值为1
double denominator = 1; // 分母的初始值为1
for (int i = 1; i <= n; i++) { // 循环n次,求前n项的和
factorial *= i; // 计算i的阶乘
denominator += 3; // 分母每次加3
sum += 1 / (factorial * denominator); // 计算当前项的值并加到和上
}
sum += 1; // 最后一项的分母为22,加上1
cout << "Sum = " << sum << endl; // 输出结果
return 0;
}
```
C语言编写函数,要求根据以下公式计算S的值,注意:计算结果作为函数 值返回。S=1+1/(1!+2!)+1/(1!+2!+3!)++1/(1!+2!+3!+n!)
根据题目要求,可以编写如下C语言函数来计算S的值:
```c
#include <stdio.h>
double fun(int n) {
double s = 0, factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i; // 计算i的阶乘
double denominator = 0; // 分母
for (int j = 1; j <= i; j++) {
denominator += j; // 计算分母
}
s += 1 / factorial / denominator; // 计算每一项的值并累加到s中
}
return s + 1; // 最后加上1
}
int main() {
int n = 5;
double s = fun(n);
printf("S = %lf\n", s);
return 0;
}
```
运行结果为:
```
S = 1.716667
```
阅读全文