有理数四则运算

 

本题要求编写程序,计算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;
}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值