1088. Rational Arithmetic 解析

难点主要在分式的通分上面,转化成求最大公因数的问题。

#include <iostream>
#include <climits>
#include <map>

using namespace std;

struct Rational {
	long int fra;
	long int dec;
};
Rational r1, r2;
int pos = 1;

int gcd(long int a, long int b) {
	if (b == 0) return a;
	else return gcd(b, a%b);
}


void printFra(long int fra, long int dec) {
	long int d = LONG_MAX;
	//有理化
	if ((fra > dec || -fra > dec) && fra % dec != 0) {
		d = fra / dec;
		fra > 0 ? fra = fra : fra = -fra;
		fra = fra % dec;
	}
	else if (fra == 0 || (fra >= dec || -fra >= dec) && fra % dec == 0){
		if(fra < 0 )
			printf("(%ld)", fra / dec);
		else
			printf("%ld", fra / dec);
		return;
	}
	
	//通分	
	int tfra = fra;
	if (fra < 0) {
		tfra = -fra;
	}
	int factor = gcd(tfra, dec);
	fra /= factor;
	dec /= factor;

	//输出
	if (d != LONG_MAX) {
		if (d < 0) {
			cout << "(" << d << " " << fra << "/" << dec << ")";
		}
		else
			cout << d << " " << fra << "/" << dec ;
	}
	else {
		if (fra < 0)
			cout << "(" << fra << "/" << dec << ")";
		else
			cout <<  fra << "/" << dec ;
	}

}

int main() {
	cin >> r1.fra;
	cin.get();
	cin >> r1.dec;

	cin >> r2.fra;
	cin.get();
	cin >> r2.dec;

	Rational a;
	//加法
	printFra(r1.fra, r1.dec);
	cout << " + ";
	printFra(r2.fra, r2.dec);
	cout << " = ";
	a.fra = r1.fra * r2.dec + r2.fra * r1.dec;
	a.dec = r1.dec * r2.dec;
	printFra(a.fra, a.dec);
	cout << endl;


	//减法
	printFra(r1.fra, r1.dec);
	cout << " - ";
	printFra(r2.fra, r2.dec);
	cout << " = ";
	a.fra = r1.fra * r2.dec - r2.fra * r1.dec;
	a.dec = r1.dec * r2.dec;
	printFra(a.fra, a.dec);
	cout << endl;

	//乘法
	printFra(r1.fra, r1.dec);
	cout << " * ";
	printFra(r2.fra, r2.dec);
	cout << " = ";
	a.fra = r1.fra * r2.fra;
	a.dec = r1.dec * r2.dec;
	printFra(a.fra, a.dec);
	cout << endl;

	//除法
	printFra(r1.fra, r1.dec);
	cout << " / ";
	printFra(r2.fra, r2.dec);
	cout << " = ";
	if (r2.fra == 0) {
		cout << "Inf" << endl;
	}
	else {
		if (r2.fra < 0) {
			r2.dec = -r2.dec;
			r2.fra = -r2.fra;
		}
		a.fra = r1.fra * r2.dec;
		a.dec = r1.dec * r2.fra;
		printFra(a.fra, a.dec);
		cout << endl;
	}
	

	return 0;



}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值