1. 程式人生 > 其它 >PAT (Basic Level) Practice 1034 有理數四則運算 (20 分)

PAT (Basic Level) Practice 1034 有理數四則運算 (20 分)

題目:1034 有理數四則運算 (20 分)

來源:PAT (Basic Level) Practice

傳送門 1034 有理數四則運算

題面

思路:模擬一遍即可,記得開long long,注意約分等,具體看程式碼

Code

點選檢視程式碼
#include <iostream>
#include <cmath>
#include <algorithm>
#include <string>
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {
	while (b ^= a ^= b ^= a %= b);
	return a;
}

void setType(ll x, ll y) {
	if (y == 0){
    	cout << "Inf";
		return;
    }
	else if (x == 0) {
		cout << 0;
        return;
	}
	else {
		ll t = gcd(abs(x),abs(y));
		if (abs(x) < abs(y)) {
			if (x*y>0)cout << x/t << "/" << abs(y/t);
			else cout << "(-" << abs(x/t) << "/" << abs(y/t)<<")";
		}
		else {
			bool flag = ((x < 0 && y>0) || (x > 0 && y < 0));
			if(flag)cout<<"(-";
			ll k = abs(x) / abs(y);
			x = abs(x) - abs(k * y);
			ll ff = gcd(abs(x),abs(y));
			if(x == 0)cout<<k;
			else cout << k << " " << abs(x / ff) << "/" << abs(y / ff);
			if(flag)cout<<")";
		}	
	}

}

int main() {
	string s1, s2;
	cin >> s1 >> s2;
	ll a1 = 0, b1 = 0, a2 = 0, b2 = 0, zs = 0;
	for (ll i = 0; i < s1.size(); i++) {
		if (s1[i] <= '9' && s1[i] >= '0') {
			b1 = b1 * 10 + s1[i] - '0';
		}
		else if (s1[i] == '/') {
			a1 = b1;
			b1 = 0;
			if (s1[0] == '-')a1 = -a1;
		}
	}
	for (ll i = 0; i < s2.size(); i++) {
		if (s2[i] <= '9' && s2[i] >= '0') {
			b2 = b2 * 10 + s2[i] - '0';
		}
		else if (s2[i] == '/') {
			a2 = b2;
			b2 = 0;
			if (s2[0] == '-')a2 = -a2;
		}
	}
	setType(a1, b1); 
	cout<<" + ";
	setType(a2, b2);
	cout<<" = "; 
	setType(a1 * b2 + b1 * a2, b1 * b2); 
	cout<<"\n";
	
	setType(a1, b1); 
	cout<<" - ";
	setType(a2, b2); 
	cout<<" = "; 
	setType(a1 * b2 - b1 * a2, b1 * b2); 
	cout<<"\n";
	
	setType(a1, b1); 
	cout<<" * "; 
	setType(a2, b2); 
	cout<<" = "; 
	setType(a1 * a2, b1 * b2); 
	cout<<"\n";
	
	setType(a1, b1); 
	cout<<" / "; 
	setType(a2, b2); 
	cout<<" = "; 
	setType(a1 * b2, b1 * a2);
	cout<<"\n";

	return 0;
}