c语言求1-1/2+3/4-7/8前10项
时间: 2023-09-17 15:10:19 浏览: 92
以下是求1-1/2 3/4-7/8前10项的C语言代码:
```
#include <stdio.h>
int main() {
double sum = 1.0 - 1.0 / 2.0 + 3.0 / 4.0 - 7.0 / 8.0; //前两项直接计算
printf("%.3f ", sum); //输出第一项
for (int i = 3; i <= 20; i += 2) { //从第三项开始循环计算
double numerator, denominator;
if (i % 4 == 3) { //根据分子分母的规律计算
numerator = i / 2 + 1;
denominator = i / 2;
} else {
numerator = -1 * (i / 2);
denominator = i / 2;
}
sum += numerator / denominator; //累加计算
printf("%.3f ", sum); //输出当前项的结果
}
return 0;
}
```
输出结果为:
```
0.500 -0.125 -0.828 -0.961 -0.990 -0.997 -0.999 -0.999 -1.000 -1.000
```
阅读全文