求Y=1-1/2+1/3-1/4+...-1/2*n 的前n项之
时间: 2023-11-19 20:04:49 浏览: 82
求出如下分数序列的前n项之和.pdf
以下是两种C语言求Y=1-1/2+1/3-1/4+...-1/2*n的前n项之和的例子:
1.使用函数求解
```c
#include <stdio.h>
float baz(int k);
int main() {
int n;
printf("输入表达式中n的值:");
scanf("%d", &n);
printf("表达式的值=%f\n", baz(n));
}
float baz(int k) {
float sum = 0, t = 1.0, n = 1.0;
while (k > 0) {
k--;
sum = sum + t * 1.0 / n;
t = -1 * t;
n++;
}
return (sum);
}
```
2.使用循环求解
```c
#include <stdio.h>
int main() {
int i, n, flag = 1;
float s = 0;
printf("put in n:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
s += 1.0 / i * flag;
flag *= -1;
}
printf("%f\n", s);
return 0;
}
```
阅读全文