c语言1+1/3!+1/5!+1/7!+……+1/21!代码
时间: 2024-01-27 20:04:46 浏览: 79
以下是C语言计算1+1/3!+1/5!+1/7!+……+1/21!的代码:
```c
#include <stdio.h>
#include <math.h>
int main() {
int i, j;
double sum = 0.0, ret = 1.0;
for (i = 1; i <= 21; i += 2) {
ret = 1.0;
for (j = 1; j <= i; j++) {
ret *= j;
}
sum += 1.0 / ret;
}
printf("结果为 %lf\n", sum);
return 0;
}
```
该代码使用了两个循环,外层循环控制分母的值,内层循环计算分母的阶乘。最后将每一项的倒数加起来即可得到结果。
相关问题
c语言求1+1/1!+1/2!……+1/n!的代码
以下是用C语言实现求解1+1/1!+1/2!+...+1/n!的代码:
```
#include <stdio.h>
double factorial(int n); // 声明函数
int main()
{
int n;
double sum = 0.0;
printf("请输入n的值:");
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
sum += 1.0 / factorial(i); // 求和
}
printf("1+1/1!+1/2!+...+1/%d!的值为:%lf\n", n, sum);
return 0;
}
double factorial(int n)
{
double result = 1.0;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
```
用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
```
阅读全文