用C语言编写1+1/1!+1/2!+1/3!+...+1/n!
时间: 2023-11-20 13:07:55 浏览: 347
c++求1+1/2+1/3+...+1/n
5星 · 资源好评率100%
以下是两种C语言编写1+1/1!+1/2!+1/3!+...+1/n!的例子:
1.使用for循环计算前n项
```c
#include <stdio.h>
void main()
{
int i, n;
double sum = 1, t = 1;
printf("输入n:\n");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
t = t * i; sum = sum + 1 / t;
}
printf("e=%lf", sum);
}
```
2.使用for循环计算前n项并输出每一项的和
```c
#include <stdio.h>
int main()
{
int n;
float sum = 0;
printf("请输入一个通项n:\n");
scanf("%d", &n);
for (int j = 1; j <= n; j++)
{
float t = 1;
for (int i = 1; i <= j; i++)
{
t *= i;
}
sum += 1.0 / t;
}
printf("1+1/1!+1/2!+1/3!+...+1/n!=%.3f\n", sum);
return 0;
}
```
阅读全文