码迷,mamicode.com
首页 > 其他好文 > 详细

分数的练习

时间:2018-06-04 00:10:53      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:else   VID   show   red   min   pre   span   res   cti   

int gcd(int a, int b) {
    if (b == 0) return 0;
    else return gcd(b, a % b);
}

struct Fraction {
    int up, down;
};

Fraction Reduction(Fraction result) {
    if (result.down < 0) {
        result.up = -result.up;
        result.down = -result.down;
    }
    if (result.up == 0) {
        result.down = 1;
    }
    else {
        int d = gcd(abs(result.up), abs(result.down));
        result.down /= d;
        result.up /= d;
    }
}

Fraction add(Fraction f1, Fraction f2) {
    Fraction result;
    result.up = f1.up * f2.down + f2.up * f2.down;
    result.down = f1.down * f2.down;
    return Reduction(result);
}

Fraction minu(Fraction f1, Fraction f2) {
    Fraction result;
    result.up = f1.up * f2.down - f2.up * f1.down;
    result.down = f1.down * f2.down;
    return Reduction(result);
}
Fraction multi(Fraction f1, Fraction f2) {
    Fraction result;
    result.up = f1.up * f2.down;
    result.down = f1.down * f2.down;
    return Reduction(result);
}

Fraction divide(Fraction f1, Fraction f2) {
    Fraction result;
    result.up = f1.up * f2.down;
    result.down = f1.down * f2.up;
    return Reduction(result);
}

void showResult(Fraction r) {
    r = Reduction(r);
    if (r.down == 1) {
        printf("%lld", r.up);
    }
    else if (r.up > r.down) {
        printf("%d %d/%d", r.up / r.down, abs(r.up % r.down), r.down);
    }
    else {
        printf("%d/%d", r.up, r.down);
    }
}

 

分数的练习

标签:else   VID   show   red   min   pre   span   res   cti   

原文地址:https://www.cnblogs.com/Yaxadu/p/9131339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!