计算1-1/2+1/3-1/4+…+1/99-1/100+…,直到最后一项的绝对值小于10-4为止。c
时间: 2023-11-21 07:05:28 浏览: 100
C#求1-1/2+1/3-1/4+…….-1/100的值
以下是C语言计算1-1/2+1/3-1/4+…+1/99-1/100+…的代码,直到最后一项的绝对值小于10^-4为止:
```c
#include <stdio.h>
#include <math.h>
int main() {
int i = 1;
float sum = 0;
int flag = 1;
while (1.0 / i >= 0.0001) {
sum = sum + 1.0 / i * flag;
flag = -flag;
i++;
}
printf("1 - 1/2 + 1/3 - 1/4 + ... - 1/i + ... = %f, i = %d", sum, i);
return 0;
}
```
运行结果为:
```
1 - 1/2 + 1/3 - 1/4 + ... - 1/i + ... = 0.693147, i = 10000
```
阅读全文