来看看循环的一个c程序

任意读入 x 的值(0<x<1),使用递推法计算 x- x2 + x3- x4 +…… -x2n + x2n+1……的值。当某项的绝对值小于 10-6时终止。(当 x 为 0.5 时,和值为 0.333334),(系统函数 fabs(x)的功能是计算 x 的绝对值,前面需加 math .h)。

参考,

#include <stdio.h>
#include <math.h>

#define DELTA (1e-6)

int main()
{
    double x;
    double res = 0;
    bool positive = true;

    while (scanf("%lf", &x) != EOF)
    {
        if (x <= 0 || x >= 1) continue; // 过滤(0,1)以外的x值
        if (fabs(x) < DELTA) break;
        res += positive ? x : -x; // 根据符号加入计算式
        positive = !positive; // 反转符号
    }
    printf("%lf\n", res);

    return 0;
}