PAT甲级1088 【Rational Arithmetic】 (20)

题目链接

分析:分数的四则运算,模拟是最烦的,注意负号一直在分子位置处,输出负的假分数时,分子不用输出负号。

#include<stdio.h>

typedef long long ll;
ll abs(ll a){
	if(a < 0) return -a;
	return a;
}
ll gcd(ll a, ll b){
	if(b == 0) return a;
	return gcd(b, a%b);
}
void simplify(ll &a, ll &b){
	if(a == 0 || b == 0) return ;
	ll gcd1 = gcd(a, b);
	a /= gcd1;
	b /= gcd1;
	if(b < 0) {
		b = -b;
		a = -a;
	}
}
void printab(ll a1, ll b1){
	if(a1 < 0) printf("(");
	if(b1 == 1 || a1 == 0) printf("%lld", a1);
	else {
		if(a1/b1 == 0) printf("%lld/%lld", a1, b1);
		else printf("%lld %lld/%lld", a1/b1, abs(a1)%b1, b1);
	}
	if(a1 < 0) printf(")");
}
void show(ll a1, ll b1, ll a2, ll b2, ll resa, ll resb, char ch, int flag){
	simplify(a1, b1);
	simplify(a2, b2);
	simplify(resa, resb);
	printab(a1, b1);
	printf(" %c ", ch);
	printab(a2, b2);
	printf(" = ");
	if(flag) {
		printf("Inf\n");
		return ;
	}
	printab(resa, resb);
	printf("\n");
}

void plus(ll a1, ll b1, ll a2, ll b2){
	ll resa, resb;
	resa = a1*b2+a2*b1;
	resb = b1*b2;
	show(a1, b1, a2, b2, resa, resb, '+', 0);
}
void sub(ll a1, ll b1, ll a2, ll b2){
	ll resa, resb;
	resa = a1*b2-a2*b1;
	resb = b1*b2;
	show(a1, b1, a2, b2, resa, resb, '-', 0);
}
void product(ll a1, ll b1, ll a2, ll b2){
	ll resa, resb;
	resa = a1*a2;
	resb = b1*b2;
	show(a1, b1, a2, b2, resa, resb, '*', 0);
}
void div(ll a1, ll b1, ll a2, ll b2){
	ll resa, resb, gcd1;
	resa = a1*b2;
	resb = b1*a2;
	if(resb == 0) show(a1, b1, a2, b2, resa, resb, '/', 1);
	else {
		show(a1, b1, a2, b2, resa, resb, '/', 0);
	}
}

int main(){
	//freopen("in.txt", "r", stdin);
	ll a1, a2, b1, b2, gcd1, gcd2;
	scanf("%lld/%lld %lld/%lld", &a1, &b1, &a2, &b2);
	plus(a1, b1, a2, b2);
	sub(a1, b1, a2, b2);
	product(a1, b1, a2, b2);
	div(a1, b1, a2, b2);
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值