c语言计算N的阶乘,要求调用函数S=1+1/(1+4!)+1/(1+4!+7!)+…+1/(1+4!+7!+…+19)
时间: 2023-11-20 12:07:11 浏览: 42
以下是C语言计算N的阶乘并调用函数计算S的代码,其中包括计算阶乘的函数fac和计算S的函数sum:
```c
#include <stdio.h>
#include <stdlib.h>
int fac(int n) //阶乘函数
{
int i = 0;
int y = 1; //用来存返回值
if (0 == n || 1 == n) {
return 1;
} else {
for (i = 2; i <= n; i++) {
y *= i;
}
return y;
}
}
double sum(int n) //求和函数
{
int i = 0; //循环变量
double sum = 0; //和
int j = 1; //用来存储分母
for (i = 1; i <= n; i++) {
sum += 1.0 / j;
j += fac(3 * i + 1); //计算下一个分母
}
return sum;
}
int main()
{
int n = 0;
printf("请输入n:>");
scanf("%d", &n);
printf("S = %lf\n", sum(n));
system("pause");
return 0;
}
```
相关问题
c语言要求调用函数S=1+1/(1+4!)+1/(1+4!+7!)+…+1/(1+4!+7!+…+19)计算N的阶乘
以下是C语言代码,用于计算S=1+1/(1+4!)+1/(1+4!+7!)+…+1/(1+4!+7!+…+19!),其中N为19的阶乘:
```c
#include <stdio.h>
#include <stdlib.h>
int fac(int n) // 阶乘函数
{
int i = 0;
int y = 1; // 用来存返回值
if (0 == n || 1 == n) {
return 1;
} else {
for (i = 2; i <= n; i++) {
y *= i;
}
return y;
}
}
double sum(int n) // 求和函数
{
int i = 0; // 循环变量
double s = 0; // 和
int f = 1; // 阶乘
for (i = 0; i <= n; i += 3) {
f *= fac(i + 4);
s += 1.0 / (1 + f);
}
return s;
}
int main()
{
int n = 19;
printf("sum = %lf\n", sum(n));
system("pause");
return 0;
}
```
c语言用函数定义和调用计算s = 1!+2!+3!+…+n!的源程序,书写阶乘函数
以下是C语言用函数定义和调用计算s = 1!+2!+3!+…+n!的源程序,以及阶乘函数的代码:
```c
#include <stdio.h>
// 阶乘函数
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
// 计算1!+2!+3!+...+n!的函数
int sumOfFactorials(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i); }
return sum;
}
// 主函数
int main() {
int n;
printf("请输入一个正整数n:");
scanf("%d", &n);
printf("1!+2!+3!+...+%d! = %d\n", n, sumOfFactorials(n));
return 0;
}
```
在上面的代码中,`factorial`函数用于计算阶乘,`sumOfFactorials`函数用于计算1!+2!+3!+...+n!,`main`函数用于读取用户输入的n并输出结果。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)