c语言求Y=1-1/2+1/3-1/4+...-1/2*n 的前n项之和
时间: 2023-11-20 21:06:20 浏览: 80
以下是两种C语言求Y=1-1/2+1/3-1/4+...-1/2*n 的前n项之和的例子:
1.使用for循环计算前n项和:
```c
#include <stdio.h>
int main() {
int n, flag = 1;
float s = 0;
printf("请输入n:");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
s += 1.0 / i * flag;
flag *= -1;
}
printf("前%d项和为%f\n", n, s);
return 0;
}
```
2.使用函数进行封装:
```c
#include <stdio.h>
float getsum(int n) {
int flag = 1;
float result = 0;
for (int i = 1; i <= n; i++) {
result += 1.0 / i * flag;
flag *= -1;
}
return result;
}
int main() {
int n = 0;
printf("请输入n:");
scanf("%d", &n);
printf("前%d项和为%f\n", n, getsum(n));
return 0;
}
```
阅读全文