编程求1-1/2+1/3-1/4+…+1/99-1/100
时间: 2024-01-29 18:04:55 浏览: 84
以下是两种编程求解1-1/2+1/3-1/4+…+1/99-1/100的例子:
1. 使用C语言编程求解:
```c
#include <stdio.h>
int main() {
int i;
double sum = 0;
int flag = 1;
for (i = 1; i <= 100; i++) {
sum = sum + flag * (1.0 / i);
flag = -flag;
}
printf("1-1/2+1/3-1/4+...+1/99-1/100的值为:%lf", sum);
return 0;
}
```
2. 使用C语言编程求解,先求1+1/3+1/5+...+1/99,再求1/2+1/4+...+1/100,后结果相减:
```c
#include <stdio.h>
int main() {
float i, j;
float sum = 0, sum1 = 0, sum2 = 0;
for (i = 1; i <= 100; i += 2) {
sum1 = sum1 + 1 / i;
}
printf("总和sum1=%f\n", sum1);
for (j = 2; j <= 100; j += 2) {
sum2 = sum2 + 1 / j;
}
printf("总和sum2=%f\n", sum2);
sum = sum1 - sum2;
printf("sum=%.2f\n", sum);
return 0;
}
```
阅读全文