本题要求编写程序,计算2个有理数的和、差、积、商。
输入描述:
输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分 母不为0。
输出描述:
分别在4行中按照“有理数1 运算符 有理数2 = 结果”的格式顺序输出2个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的 最简形式“k a/b”,其中k是整数部分,a/b是最简分数部分;若为负数,则须加括号;若除法分母为0,则输出“Inf”。题目保证正确的输出中 没有超过整型范围的整数。
示例1
输入
5/3 0/6
输出
1 2/3 + 0 = 1 2/3 1 2/3 - 0 = 1 2/3 1 2/3 * 0 = 0 1 2/3 / 0 = Inf
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
//结构体定义形式
struct Fraction{
ll son;//分子
ll mother;//分母
};
//最大公约数:辗转相除
ll gcd(ll a,ll b){
if(b==0){
return a;
}else{
return gcd(b,a%b);
}
}
//分数的约分
Fraction reduction(Fraction &a){
if(a.son==0){
a.mother=1;//对分子为0的分数后续直接输出0
return a;
}
if(a.mother<0){//题中明确规定负号只能在分子前面
a.mother=-a.mother;
a.son=-a.son;
}
//进行约分(分子可能有负号,用绝对值处理)
ll d=gcd(abs(a.son),a.mother);
a.mother/=d;
a.son/=d;
return a;
}
//分数的加法
Fraction add(Fraction a,Fraction b){
Fraction c;
c.son=a.son*b.mother+b.son*a.mother;
c.mother=a.mother*b.mother;
return c;
}
//分数的减法
Fraction sub(Fraction a,Fraction b){
Fraction c;
c.son=a.son*b.mother-b.son*a.mother;
c.mother=a.mother*b.mother;
return c;
}
Fraction mul(Fraction a,Fraction b){
Fraction c;
c.son=a.son*b.son;
c.mother=a.mother*b.mother;
return c;
}
Fraction did(Fraction a,Fraction b){
Fraction c;
c.son=a.son*b.mother;
c.mother=a.mother*b.son;
return c;
}
void output(Fraction a){
a=reduction(a);
if(a.son<0){
cout<<"(";
}
if(a.mother==1){
cout<<a.son;
if(a.son<0){
cout<<")";
}
return;
}
//cout<<"son="<<a.son<<" "<<"mon="<<a.mother<<endl;
if(abs(a.son)>a.mother){
cout<<a.son/a.mother<<" "<<abs(a.son)%a.mother<<"/"<<a.mother;
}else{
cout<<a.son<<"/"<<a.mother;
}
if(a.son<0){
cout<<")";
}
}
int main(){
Fraction a,b;
scanf("%lld/%lld %lld/%lld",&a.son,&a.mother,&b.son,&b.mother);
output(a);cout<<" + ";output(b);cout<<" = ";output(add(a,b));cout<<endl;
output(a);cout<<" - ";output(b);cout<<" = ";output(sub(a,b));cout<<endl;
output(a);cout<<" * ";output(b);cout<<" = ";output(mul(a,b));cout<<endl;
output(a);cout<<" / ";output(b);cout<<" = ";
if(b.son==0){
cout<<"Inf";
}else
output(did(a,b));
cout<<endl;
return 0;
}