1088 Rational Arithmetic (20分)
题目链接
#include<iostream>
#include<cmath>
using namespace std;
#include<cstdlib>typedef long long ll;struct Fraction{
ll up;ll down;
}fraction[2];char sign[4] = {
'+', '-', '*', '/'};ll gcd(ll a, ll b)
{
return b==0 ? a : gcd(b, a%b);
}
Fraction reduction(Fraction a)
{
if(a.down < 0){
a.down = -a.down;a.up = -a.up;}else if(a.up == 0)a.down = 1;else{
int d = gcd(abs(a.up), abs(a.down));a.up /= d;a.down /= d;}return a;
}Fraction add(Fraction a, Fraction b)
{
Fraction temp;temp.up = a.up * b.down + a.down * b.up;temp.down = a.down * b.down;return reduction(temp);
}Fraction sub(Fraction a, Fraction b)
{
Fraction temp;temp.up = a.up * b.down - a.down * b.up;temp.down = a.down * b.down;return reduction(temp);
}Fraction multi(Fraction a, Fraction b)
{
Fraction temp;temp.up = a.up * b.up;temp.down = a.down * b.down;return reduction(temp);
}Fraction divide(Fraction a, Fraction b)
{
Fraction temp;temp.up = a.up * b.down;temp.down = a.down * b.up;return reduction(temp);
}void print(Fraction a)
{
a = reduction(a); if(a.up < 0)cout<<"(";if(a.down == 1)cout<<a.up;else if(a.up == 0)cout<<"0";else if(abs(a.up) > a.down)cout<<a.up/a.down<<" "<<abs(a.up) % (int)a.down<<"/"<<a.down;else{
cout<<a.up<<"/"<<a.down;}if(a.up < 0)cout<<")";
}int main()
{
for(int i=0;i<2;i++){
scanf("%lld/%lld", &fraction[i].up, &fraction[i].down);}for(int i=0;i<4;i++){
print(fraction[0]);cout<<" "<<sign[i]<<" ";print(fraction[1]);cout<<" = ";switch(i){
case 0:print(add(fraction[0], fraction[1]));break;case 1:print(sub(fraction[0], fraction[1]));break;case 2:print(multi(fraction[0], fraction[1]));break;case 3:if(fraction[1].up == 0)cout<<"Inf"<<endl;elseprint(divide(fraction[0], fraction[1]));break;}if(i!=3)cout<<endl;}return 0;
}