难点主要在分式的通分上面,转化成求最大公因数的问题。
#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;
}