设计一个函数my_sum(n),求 1/2−2/3+3/5−5/8+8/13−… 的前n项的和 c语言
时间: 2023-12-12 21:36:01 浏览: 87
以下是C语言实现的my_sum函数,用于求解1/2−2/3+3/5−5/8+8/13−…的前n项和:
```c
#include <stdio.h>
double my_sum(int n) {
double sum = 0.0;
double a = 1.0, b = 2.0, c;
int i;
for (i = 1; i <= n; i++) {
sum += a / b;
c = a + b a = b;
b = c;
if (i % 2 == 0) {
sum -= a / b;
c = a + b;
a = b;
b = c;
}
}
return sum;
}
int main() {
int n = 6;
printf("前%d项和为:%lf\n", n, my_sum(n));
return 0;
}
```
阅读全文