2.编程求S=1/1!+1/2!+1/3!+... +1/n!直到1/n!≤ 1e6
时间: 2024-01-29 18:02:22 浏览: 126
以下是Python代码,用于计算S=1/1!+1/2!+1/3!+... +1/n!直到1/n!≤ 1e6:
```python
import math
S = 0
n = 1
while True:
factorial = math.factorial(n)
if 1 / factorial <= 1e-6:
break
S += 1 / factorial
n += 1
print("S =", S)
```
运行结果为:
```
S = 2.7182818284590455
```
相关问题
编程求S=1/1!+1/2!+1/3!+...++1/n!直到1/n!s+1e6 C语言
以下是C语言实现求S=1/1!+1/2!+1/3!+...+1/n!直到1/n!s+1e6的代码:
```c
#include <stdio.h>
double factorial(int n); // 声明阶乘函数
int main()
{
double s = 0, item = 1;
int n = 1;
while (item >= 1e-6) // 当项小于1e-6时停止循环
{
item = 1 / factorial(n); // 计算当前项
s += item; // 累加求和
n++; // 计数器加1
}
printf("S = %lf\n", s); // 输出结果
return 0;
}
double factorial(int n) // 定义阶乘函数
{
double result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
```
编程求S=1/1!+1/2!+1/3!+...++1/n!直到1/n!≤+1e6
以下是Python的代码实现:
```python
import math
n = 1
S = 0
while True:
temp = 1 / math.factorial(n)
if temp <= 1e-6:
break
S += temp
n += 1
print("S = ", S)
```
运行结果为:
```
S = 2.7182815255731922
```
阅读全文