1088 Rational Arithmetic (20 分)-PTA甲级-分数四则运算、运算符重载

搞了两个小时才搞出来,就当练习运算符重载了。极其讨厌这种细节一大堆的题,而且还是20分的第一题,希望考场上不要碰到。

坑点:

分母可以为负数

#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
typedef long long ll;
const int maxn = 205,inf=1e9;
ll gcd(ll a, ll b)
{
	return b == 0 ? a : gcd(b, a%b);
}
struct node
{
	ll up, down;
	node(){}
	node(ll u,ll d):up(u),down(d){}		//这里参数列表一开始写成int了,害的找了一个多小时bug
	friend node operator+(const node &a, const node &b)
	{
		return node (a.up*b.down + b.up*a.down,a.down*b.down);
	}
	friend node operator-(const node &a, const node &b)
	{
		return a+node (b.up*-1,b.down);
	}
	friend node operator*(const node &a, const node &b)
	{
		return node (a.up*b.up, a.down*b.down);
	}
	friend node operator/(const node &a, const node &b)
	{
		return a*node (b.up<0?-b.down:b.down, abs(b.up));
	}
	friend ostream& operator<<(ostream &os, const node &a)
	{
		ll up = a.up, down = a.down;
		if (up&&down)			//化简
		{
			ll d = gcd(abs(up), abs(down));
			up /= d;
			down /= d;
		}
		if (up == 0)
		{
			os << "0";
			return os;
		}
		if (up < 0)
			os << "(-";
		if (abs(up) >= down)
			os << abs(up) / down;
		if (abs(up) % down)
		{
			if (abs(up) >= down)
				os << " ";
			os << abs(up) % down << "/" << down;
		}
		if (up < 0)
			os << ")";
		return os;
	}
	friend istream& operator >> (istream &is, node &a)
	{
		string s;
		is >> s;
		int p = s.find("/");
		ll x, y;
		sscanf(s.substr(0, p).c_str(), "%lld", &x);
		sscanf(s.substr(p + 1, s.size() - p - 1).c_str(), "%lld", &y);
		if (x&&y)
		{
			ll d = gcd(abs(x), abs(y));
			x /= d;
			y /= d;
		}
		a = node(y < 0 ? -x : x, abs(y));
		return is;
	}
};

int main()
{	
	node a ,b;
	cin >> a >> b;
	char op[4] = { '+','-','*','/' };
	for (int i = 0; i < 4; i++)
	{
		cout << a << " " << op[i] << " " << b << " = ";
		switch (i)
		{
		case 0:cout << a + b; break;
		case 1:cout << a - b; break;
		case 2:cout << a * b; break;
		}
		if (i == 3)
		{
			if (b.up != 0)
				cout << a / b;
			else
				cout << "Inf";
		}
		cout << endl;
	}
	return 0;
}

上一篇:[洛谷 P4314] CPU监控


下一篇:关于imwheel的配置