s=1+1/1!+1/2!+1/4!
时间: 2023-11-19 14:07:22 浏览: 28
以下是Python代码实现:
```python
import math
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def sum(n):
s = 0
for i in range(n+1):
s += 1/factorial(i)
return s
n = int(input("请输入n的值:"))
print("s的值为:", sum(n))
```
输出结果:
```
请输入n的值:4
s的值为: 2.708333333333333
```
相关问题
用c++表达s=1+1/1!+1/2!+1/4!
以下是C++代码实现s=1+1/1!+1/2!+1/4!的计算:
```c++
#include <iostream>
using namespace std;
int main() {
double s = 1, t = 1;
for (int i = 1; i <= 4; i++) {
t *= i;
s += 1 / t;
}
cout << "s = " << s << endl;
return 0;
}
```
输出结果为:s = 2.70833
s = 1 + 1 / 2! + 1 / 3! + 1 / 4! + … + 1 / n!
以下是一个C语言的程序,用于计算 s = 1 + 1 / 2! + 1 / 3! + 1 / 4! + … + 1 / 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用于计算s的值。在主函数main中,我们首先从终端输入n的值,然后调用sum函数计算s的值,并将结果打印出来。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![m](https://img-home.csdnimg.cn/images/20210720083646.png)
![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)