C语言求1+1/2!+1/3!+······+1/n!
时间: 2023-07-30 15:13:01 浏览: 707
下面是使用C语言计算1+1/2!+1/3!+······+1/n!的代码实现:
```c
#include <stdio.h>
int main() {
int n = 10; // 计算1+1/2!+1/3!+······+1/n!
double sum = 1.0; // 存储累加和,初始值为1(第一项)
double factorial = 1.0; // 存储阶乘,初始值为1(第一项的分母)
for (int i = 2; i <= n; i++) {
factorial *= i; // 计算i的阶乘
sum += 1.0 / factorial; // 累加1/i!的值
}
printf("1+1/2!+1/3!+······+1/n! = %lf\n", sum);
return 0;
}
```
在代码中,使用sum变量存储累加和,初始值为1(第一项),使用factorial变量存储阶乘,初始值为1(第一项的分母),然后通过for循环依次计算每一项的值并累加到sum中。最后输出累加和的值即可。
相关问题
c语言编程求1+1/1!+1/2!+1/3!+…+1/n!,直到第10项为止。
以下是C语言编程求1+1/1!+1/2!+1/3!+…+1/n!,直到第10项为止的代码:
```c
#include <stdio.h>
int main() {
int n = 10;
double sum = 1, t = 1;
for (int i = 1; i <= n; i++) {
t *= i;
sum += 1 / t;
}
printf("sum = %lf", sum);
return 0;
}
```
用c语言编程求1+1/1!+1/2!+1/3!+……+1/10!
以下是用C语言编写求1+1/1!+1/2!+1/3!+……+1/10!的代码:
```c
#include <stdio.h>
int main() {
int i, j;
double sum = 0, factorial = 1;
for (i = 1; i <= 10; i++) {
factorial = 1;
for (j = 1; j <= i; j++) {
factorial *= j;
}
sum += 1.0 / factorial;
}
printf("1+1/1!+1/2!+1/3!+……+1/10!=%lf\n", sum);
return 0;
}
```
运行结果为:
```
1+1/1!+1/2!+1/3!+……+1/10!=2.718282
```
阅读全文