用c语言编写函数,计算 1/1! + 1/2! + 1/3! + ... + 1/n!。在主函数中输人 n 的值,调用函数完成计算并输出计算结果,结果保留两位小数。。
时间: 2023-10-07 22:06:17 浏览: 63
```c
#include <stdio.h>
double factorial(int n); // 声明计算阶乘的函数
double calculate(int n); // 声明计算结果的函数
int main() {
int n;
printf("请输入 n 的值:");
scanf("%d", &n);
printf("计算结果为:%.2lf", calculate(n));
return 0;
}
double factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
double calculate(int n) {
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += 1 / factorial(i);
}
return sum;
}
```
相关问题
C语言,编写函数计算N!,调用该函数计算下式的值:s=1+1/(1+4!)+1/(1+4!+7!)+...+1/(1+4!+7!+....+19!)
以下是计算N!的函数实现:
```c
#include <stdio.h>
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
```
接下来可以用该函数计算出s的值:
```c
#include <stdio.h>
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
double s = 1.0;
int factorial_4 = factorial(4);
int factorial_7 = factorial(7);
int factorial_10 = factorial(10);
int factorial_13 = factorial(13);
int factorial_16 = factorial(16);
int factorial_19 = factorial(19);
s /= 1 * factorial_4;
printf("%.10lf\n", s);
s /= 1 * factorial_7;
printf("%.10lf\n", s);
s /= 1 * factorial_10;
printf("%.10lf\n", s);
s /= 1 * factorial_13;
printf("%.10lf\n", s);
s /= 1 * factorial_16;
printf("%.10lf\n", s);
s /= 1 * factorial_19;
printf("%.10lf\n", s);
return 0;
}
```
输出结果:
```
0.0416666667
0.0001984127
4.4040404040e-09
5.5302934439e-12
4.1901724417e-15
1.6850662441e-18
```
用C语言1、编写函数实现n! 2、通过调用第1步骤的函数计算1/1!+1/2!+...+1/8!
1. 下面是实现n!的C语言代码:
```c
#include <stdio.h>
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int n = 5;
int result = factorial(n);
printf("%d! = %d\n", n, result);
return 0;
}
```
2. 下面是通过调用factorial函数计算1/1! 1/2! ... 1/8!的C语言代码:
```c
#include <stdio.h>
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
double sum = 0;
for (int i = 1; i <= 8; i++) {
double num = 1.0 / factorial(i);
sum += num;
printf("1/%d! = %.8lf, sum = %.8lf\n", i, num, sum);
}
return 0;
}
```
希望这回答能够帮到您。如果还有其他问题,欢迎随时提出。
阅读全文