其他分享
首页 > 其他分享> > 有理数运算

有理数运算

作者:互联网

https://www.acwing.com/problem/content/description/1580/

思路:
这题思路并不难,但如果你傻乎乎的一种一种情况的输出,那会非常的繁琐,巧妙的利用一个函数来统一起来实现。

#include <iostream>

using namespace std;

typedef long long LL;

LL gcd(LL a, LL b)
{
    return b ? gcd(b, a % b) : a;
}

void print(LL a, LL b)
{
    LL d = gcd(a, b);
    a /= d, b /= d;

    if (b < 0) a *= -1, b *= -1;
    bool is_minus = a < 0;

    if (is_minus) cout << "(";

    if (b == 1) cout << a;
    else
    {
        if (abs(a) >= b) printf("%lld ", a / b), a = abs(a) % b;
        printf("%lld/%lld", a, b);
    }

    if (is_minus) cout << ")";
}

void add(LL a, LL b, LL c, LL d)
{
    print(a, b), cout << " + ", print(c, d), cout << " = ";
    a = a * d + b * c;
    b = b * d;
    print(a, b), cout << endl;
}

void sub(LL a, LL b, LL c, LL d)
{
    print(a, b), cout << " - ", print(c, d), cout << " = ";
    a = a * d - b * c;
    b = b * d;
    print(a, b), cout << endl;
}

void mul(LL a, LL b, LL c, LL d)
{
    print(a, b), cout << " * ", print(c, d), cout << " = ";
    a = a * c;
    b = b * d;
    print(a, b), cout << endl;
}

void div(LL a, LL b, LL c, LL d)
{
    print(a, b), cout << " / ", print(c, d), cout << " = ";
    if (!c) puts("Inf");
    else
    {
        a = a * d;
        b = b * c;
        print(a, b), cout << endl;
    }
}

int main()
{
    LL a, b, c, d;
    scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d);

    add(a, b, c, d);
    sub(a, b, c, d);
    mul(a, b, c, d);
    div(a, b, c, d);

    return 0;
}

标签:有理数,运算,gcd,LL,cout,printf,minus,lld
来源: https://www.cnblogs.com/xjtfate/p/16612432.html