编写程序,求1+1/1!+1/2!+1/3!+...+1/n!,并将结果存放到e (打印显示2位小数) C语言
时间: 2023-09-12 09:05:11 浏览: 61
以下是求解程序:
```c
#include <stdio.h>
int main() {
int n, i, j;
double s = 1, t = 1;
printf("请输入n:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
t *= i;
s += 1 / t;
}
printf("e = %.2f\n", s);
return 0;
}
```
运行结果:
```
请输入n:10
e = 2.72
```
相关问题
编写程序求1!+2!+3!+..+n!
以下是C语言编写程序求1!+2!+3!+..+n!的例子:
```c
#include <stdio.h>
int main()
{
int n, i, j, sum = 0, s = 1;
scanf("%d", &n); // 输入n
for (i = 1; i <= n; i++) {
s = 1; // 每次循环前将s初始化为1
for (j = 1; j <= i; j++) {
s = s * j; // 计算i的阶乘
}
sum = sum + s; // 累加阶乘之和
}
printf("%d", sum); // 输出结果
return 0;
}
```
编写程序求1! +2! +3! ..+10!
以下是C语言和Python两种编写程序求1! +2! +3! ..+10!的例子:
1.C语言程序
```c
#include <stdio.h>
int main()
{
int i, j;
double e = 1, factorial = 1;
for (i = 1; factorial >= 0.000001; i++)
{
factorial = 1;
for (j = 1; j <= i; j++)
{
factorial *= j;
}
e += 1.0 / factorial;
}
printf("e = %lf\n", e);
return 0;
}
```
2.Python程序
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
sum = 0
for i in range(1, 11):
sum += factorial(i)
print(sum) # 输出:4037913
```
阅读全文