For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.
Input Specification:
Each input file contains one test case, which gives in one line the two rational numbers in the format “a1/b1 a2/b2”. The numerators and the denominators are all in the range of long int. If there is a negative sign, it must appear only in front of the numerator. The denominators are guaranteed to be non-zero numbers.
Output Specification:
For each test case, print in 4 lines the sum, difference, product and quotient of the two rational numbers, respectively. The format of each line is “number1 operator number2 = result”. Notice that all the rational numbers must be in their simplest form “k a/b”, where k is the integer part, and a/b is the simplest fraction part. If the number is negative, it must be included in a pair of parentheses. If the denominator in the division is zero, output “Inf” as the result. It is guaranteed that all the output integers are in the range of long int.
Sample Input 1:
2/3 -4/2
Sample Output 1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
Sample Input 2:
5/3 0/6
Sample Output 2:
1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf
思路:打算分成三个步骤,第一步将所有正的分数通分或者改成真分数;第二步按照要求增加负号/括号/Inf等;第三步将+-*/的三个分数都按照格式输出。
Tips:使用分子/分母作为实参传递较方便。
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
using namespace std;
void simplest(long int m,long int n){
long int a=m;
long int b=n;
int num=0;
int temp;
while(a%b!=0){
temp=b;
b=a%b;
a=temp;
}//辗转相除法的乞丐版
m/=b;
n/=b;
if(m>n){
num=m/n;
m=m-n*num;
if(m!=0){
cout<<num<<' '<<m<<'/'<<n;
}
else{
cout<<num;
}
}
else if(m==n){
cout<<'1';
}
else{
cout<<m<<'/'<<n;
}
}//不考虑符号、零、括号、Inf的情况下的最简形式
void format(long int a,long int b){
if(b==0){
cout<<"Inf";
return;
}
if(b<0){
b=-b;
a=-a;
}//除法会使符号到分母位置
if(a==0){
cout<<'0';
return;
}
else if(a<0){
cout<<'('<<'-';
a=-a;
simplest(a,b);
cout<<')';
}
else{
simplest(a,b);
}
} //格式化输出
int main(){
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
long int a1,b1,a2,b2;
cin>>a1;cin.get();
cin>>b1>>a2;cin.get();
cin>>b2;
format(a1,b1);cout<<" + ";
format(a2,b2);cout<<" = ";
format(a1*b2+a2*b1,b1*b2);cout<<endl;
format(a1,b1);cout<<" - ";
format(a2,b2);cout<<" = ";
format(a1*b2-a2*b1,b1*b2);cout<<endl;
format(a1,b1);cout<<" * ";
format(a2,b2);cout<<" = ";
format(a1*a2,b1*b2);cout<<endl;
format(a1,b1);cout<<" / ";
format(a2,b2);cout<<" = ";
format(a1*b2,b1*a2);cout<<endl;
return 0;
}