1+1/1!+1/2!+1/3!+1/n!
时间: 2023-12-01 11:42:40 浏览: 23
以下是Python中求1+1/1!+1/2!+1/3!+1/n!的方法:
```python
import math
n = int(input("请输入n的值:"))
sum = 0
for i in range(n):
sum += 1 / math.factorial(i)
print("1+1/1!+1/2!+1/3!+1/n!的值为:", round(sum, 3))
```
相关问题
c语言求1+1/2!+……+1/n!
这道题目要求我们编写C语言程序计算1+1/2!+1/3!+1/4!+…+1/n!,其中n由终端输入,需要将计算n!定义成函数。下面是代码实现和解释:
```c
#include <stdio.h>
#include <stdlib.h>
// 阶乘函数
int fac(int n) {
int i = 0;
int y = 1; // 用来存返回值
if (0 == n || 1 == n) {
return 1;
} else {
for (i = 2; i <= n; i++) {
y *= i;
}
return y;
}
}
// 求和函数
double sum(int n) {
int i = 0; // 循环变量
double sum = 0; // 和
for (i = 1; i <= n; i++) {
sum += 1.0 / fac(i);
}
return sum;
}
int main() {
int n = 0;
printf("请输入n:>");
scanf("%d", &n);
printf("sum = %lf\n", sum(n));
system("pause");
return 0;
}
```
在这个程序中,我们定义了两个函数:fac和sum。fac函数用来计算n的阶乘,sum函数用来计算1+1/2!+1/3!+1/4!+…+1/n!的和。在sum函数中,我们调用了fac函数来计算每一项的分母。最后在主函数中,我们通过scanf函数获取用户输入的n,然后调用sum函数计算结果并输出。
c语言1+1/2!+…+1/n!
以下是C语言求1+1/2!+...+1/n!的程序:
```c
#include <stdio.h>
int main() {
int n;
float sum = 0, fac = 1;
printf("请输入一个通项n:\n");
scanf("%d", &n);//读取用户输入;
for (int j = 1; j <= n; j++) {
fac *= j;//计算阶乘
sum += 1.0 / fac;//计算累加和
}
printf("前%d项的和为%.3f", n, sum);
return 0;
}
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)