用c语言计算1/1!+1/2!+1/3!+1/6!+1/7!+1/8!+1/9!
时间: 2023-11-08 12:05:30 浏览: 101
c代码-13、功能:计算1-1/2+1/3-1/4+……+1/99-1/100。
这道题目需要用到循环和递归两种方法来计算阶乘和累加和。首先,我们需要明确阶乘的概念,即n的阶乘为n*(n-1)*(n-2)*...*1。然后,我们可以使用循环来计算每个数的阶乘,并将它们相加。具体步骤如下:
```c
#include <stdio.h>
int main() {
int i, j;
double sum = 0, factorial = 1;
for (i = 1; i <= 9; i++) {
factorial = 1; for (j = 1; j <= i; j++) {
factorial *= j;
}
sum += 1.0 / factorial;
}
printf("1/1!+1/2!+1/3!+1/6!+1/7!+1/8!+1/9!=%lf\n", sum);
return 0;
}
```
另一种方法是使用递归来计算阶乘,具体步骤如下:
```c
#include <stdio.h>
double factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int i;
double sum = 0;
for (i = 1; i <= 9; i++) {
sum += 1.0 / factorial(i);
}
printf("1/1!+1/2!+1/3!+1/6!+1/7!+1/8!+1/9!=%lf\n", sum);
return 0;
}
```
阅读全文