【演算法學習】數學專題 有理數類别範本

memcpy0發表於2020-12-16

過載了 +, -, *, /, << 操作的有理數類别範本:

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
class rational { 
private:
    ll u, d;
    ll gcd(ll a, ll b) { return !b ? a : gcd(b, a % b); }
    ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
    void reduce(ll& u, ll& d) {
        ll g = gcd(abs(u), abs(d)); //可能有負數
        u /= g, d /= g;
    }
public:
    rational(ll a, ll b) : u(a), d(b) { reduce(u, d); } //化簡
    rational operator+(const rational& t) {
		ll m = lcm(d, t.d);
		return rational(u * (m / d) + t.u * (m / t.d), m);
	}
	rational operator-(const rational& t) {
		return *this + rational(-t.u, t.d); //用+法實現-法
	}
	rational operator*(const rational& t) {
		return rational(u * t.u, d * t.d);
	}
	rational operator/(const rational& t) {
		if (t.u == 0) return rational(1, 0); //inf,分母為0 
		if (t.u < 0) return *this * rational(-t.d, -t.u); //分母<0則翻轉分子分母的符號,使得分母為正 
		return *this * rational(t.d, t.u); //用*法實現/法
	}
    friend ostream& operator<<(ostream& os, const rational& r);
};
ostream& operator<<(ostream& os, const rational& r) {
	if (r.d == 0) { os << "Inf"; return os; } //分母為0,則是除法 
	//if (r.u == 0) { os << 0; return os; } //分子為0,輸出0 
	if (r.u < 0) os << "("; //負數需要( 
	if (r.d == 1) os << r.u; //分母為1,輸出分子; 分子為0,化簡得到分母為1,也一樣輸出分子
	else if (abs(r.u) > r.d) os << r.u / r.d << " " << abs(r.u) % r.d << "/" << r.d; //假分數
	else os << r.u << "/" << r.d; //真分數 
	if (r.u < 0) os << ")";	//負數需要) 
	return os;
}
int main() {
    ll a1, b1, a2, b2;
    scanf("%lld/%lld %lld/%lld", &a1, &b1, &a2, &b2);
    rational a(a1, b1), b(a2, b2);
	cout << a << " + " << b << " = " << (a + b) << endl;
	cout << a << " - " << b << " = " << (a - b) << endl;
	cout << a << " * " << b << " = " << (a * b) << endl;
	cout << a << " / " << b << " = " << (a / b) << endl;
    return 0;
}

執行結果1:
【演算法學習】數學專題 有理數類别範本
執行結果2:
【演算法學習】數學專題 有理數類别範本

相關文章