天天看點

計算1+1/2+1/3+....+1/100的值

實作1/1-1/2+1/3-1/4+…+1/100的和。

#include <stdio.h>

#define SIGN(x) ((x) > 0 ? 1 : ((x) < 0 ? -1 : 0))

#define ABS(x) ((x) >= 0 ? (x) : -(x))

typedef long long LL;

LL gcd(LL a, LL b)

{

    return b ? gcd(b, a % b) : a;

}

typedef struct

{

    LL up;

    LL down;

} FRACTION;

void simplify(FRACTION *f)

{

    if (f->up == 0)

    {

        f->up = 0;

        f->down = 1;

    }

    else if (SIGN(f->up) * SIGN(f->down) > 0)

    {

        f->up = ABS(f->up);

        f->down = ABS(f->down);

    }

    else

    {

        f->up = -ABS(f->up);

        f->down = ABS(f->down);

    }

    LL g = gcd(ABS(f->up), f->down);

    f->up /= g;

    f->down /= g;

}

void input(FRACTION *f)

{

    scanf("%I64d%I64d", &f->up, &f->down);

    simplify(f);

}

void print(FRACTION *f)

{

    if (f->down == 1)

        printf("%I64d\n", f->up);

    else

        printf("%I64d/%I64d\n", f->up, f->down);

}

void testSimplify()

{

    FRACTION a = {4, -6}, b = {-8, -6}, c = {99, 66}, d = {0, -5};

    simplify(&a), simplify(&b), simplify(&c), simplify(&d);

    print(&a), print(&b), print(&c), print(&d);

}

LL add(FRACTION*a,FRACTION*b,FRACTION*c)

{

    LL up=a->up*b->down+a->down*b->up;

    LL down=a->down*b->down;

    c->up=up;

    c->down=down;

    simplify(c);

}

void testAdd()

{

    FRACTION a = {4, -6}, b = {-8, -6}, c;

    add(&a, &b, &c);

    print(&c);

}

int main()

{

    int i;

    FRACTION s= {0,1};

    for(i=1; i<=100; i++)

    {

        if(i%2==0)FRACTION cur= {-1,i};

        FRACTION cur= {1,i};

        add(&s,&cur,&s);

    }

    print(&s);

    return 0;

}

轉載于:https://www.cnblogs.com/eastofeden/p/7376018.html