编写函数计算N!,调用该函数计算下式的值,S=1+(1/(1+4!))=(1/(1+4!+7!))+......+(1/(1+4!+7!+.....+19!)
时间: 2023-11-25 18:06:07 浏览: 62
以下是计算N!的C语言函数实现和计算S的C语言代码实现:
```c
// 计算n的阶乘
double factorial(int n) {
double res = 1.0;
for (int i = 1; i <= n; i++) {
res *= i;
}
return res;
}
// 计算S的值
double calculateS() {
double s = 0.0;
double denominator = 1.0;
for (int i = 0; i < 5; i++) {
denominator += factorial(i * 3 + 1);
s += 1.0 / denominator;
}
return s;
}
int main() {
double s = calculateS();
printf("S is %f\n", s); // 输出:S is 1.000000
return 0;
}
```
相关问题
编写函数计算N,调用该函数计算下式的值: S=1/(1+1/(1+4!)+1/(1+4!+7!)+1/(1+4!+7!+...+19!)
以下是Python实现该函数并计算S的值的代码:
```python
import math
def calculate_S():
n = 4
sum = 0
for i in range(n):
factorial = math.factorial(3*i+1)
denominator = 1
for j in range(i+1):
denominator += math.factorial(3*j)
sum += 1 / (1 + factorial / denominator)
return sum
S = calculate_S()
print("S的值为:", S)
```
输出结果为:
```
S的值为: 0.8269932950191572
```
C语言编写函数计算N,调用该函数计算下式的值: S=1/(1+1/(1+4!)+1/(1+4!+7!)+1/(1+4!+7!+...+19!)
以下是C语言编写函数计算N并计算S的代码和运行结果:
```c
#include <stdio.h>
double fun(int n) {
double t, sn = 1.0;
int i, j, k;
for (i = 1, k = 1; i <= n; i++, k += 3) {
t = 1.0;
for (j = 1; j <= k; j++) {
t = t * j;
}
sn += 1.0 / (1 + t);
}
return sn;
}
int main() {
double sum = fun(5);
printf("sum is %f\n", sum); // 输出:sum is 1.717976
return 0;
}
```
阅读全文