分数

    科技2024-11-02  14

    分数

    1.基本运算 (+, -, *, /) (重载运算符)

    LL Abs (LL x) { return x > 0 ? x : -x; } LL gcd (LL x, LL y) { x = Abs (x), y = Abs (y); if (x > y) swap (x, y); if (x == 0) return y; else return gcd (y % x, x); } LL lcm (LL x, LL y) { return x * (y / gcd (x, y)); } struct fraction { LL a, b; void read () { scanf ("%lld %lld", &a, &b); if (b < 0) a = -a, b = -b; } fraction operator + (const fraction x) const { fraction ans; ans.b = lcm (b, x.b); ans.a = x.a * (ans.b / x.b) + a * (ans.b / b); int temp = gcd (ans.a, ans.b); ans.a /= temp, ans.b /= temp; return ans; } fraction operator * (const fraction x) const { fraction ans; LL val1 = gcd (a, x.b), val2 = gcd (b, x.a); ans.a = a * x.a / val1; ans.b = b * x.b / val2; LL temp = gcd (ans.a, ans.b); ans.a /= temp; ans.b /= temp; return ans; } fraction operator - (const fraction tem) const { fraction x, y; x.a = a, x.b = b; y.a = -tem.a; y.b = tem.b; return x + y; } fraction operator / (const fraction tem) const { fraction x, y; x.a = a; x.b = b; y.a = tem.b; y.b = tem.a; return x * y; } void write () { if (a % b == 0) printf ("%lld", a / b); else printf ("%lld/%lld", a, b); } };

    2.基本运算 (+ - * /)(运算)

    #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define LL long long LL Abs (LL x) { return x > 0 ? x : -x; } LL gcd (LL x, LL y) { x = Abs (x), y = Abs (y); if (x > y) swap (x, y); if (x == 0) return y; else return gcd (y % x, x); } LL lcm (LL x, LL y) { return x * (y / gcd (x, y)); } struct fraction { LL a, b; void read () { scanf ("%lld %lld", &a, &b); if (b < 0) a = -a, b = -b; } fraction operator + (const fraction x) const { fraction ans; ans.b = lcm (b, x.b); ans.a = x.a * (ans.b / x.b) + a * (ans.b / b); int temp = gcd (ans.a, ans.b); ans.a /= temp, ans.b /= temp; return ans; } fraction operator * (const fraction x) const { fraction ans; LL val1 = gcd (a, x.b), val2 = gcd (b, x.a); ans.a = a * x.a / val1; ans.b = b * x.b / val2; LL temp = gcd (ans.a, ans.b); ans.a /= temp; ans.b /= temp; return ans; } fraction operator - (const fraction tem) const { fraction x, y; x.a = a, x.b = b; y.a = -tem.a; y.b = tem.b; return x + y; } fraction operator / (const fraction tem) const { fraction x, y; x.a = a; x.b = b; y.a = tem.b; y.b = tem.a; return x * y; } void write () { if (a % b == 0) printf ("%lld", a / b); else printf ("%lld/%lld", a, b); } }; int main () { fraction a, b; char type[100]; a.read (); scanf ("%s", type + 1); b.read (); switch (type[1]) { case '+' : { a = a + b; a.write (); } case '-' : { a = a - b; a.write (); } case '*' : { a = a * b; a.write (); } case '/' : { a = a / b; a.write (); } } }
    Processed: 0.085, SQL: 8