PAT Basic 1034 有理数四则运算(20)

1034. 有理数四则运算(20)

时间限制
200 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue

本题要求编写程序,计算2个有理数的和、差、积、商。

输入格式:

输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分母不为0。

输出格式:

分别在4行中按照“有理数1 运算符 有理数2 = 结果”的格式顺序输出2个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的最简形式“k a/b”,其中k是整数部分,a/b是最简分数部分;若为负数,则须加括号;若除法分母为0,则输出“Inf”。题目保证正确的输出中没有超过整型范围的整数。

输入样例1:
2/3 -4/2
输出样例1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
输入样例2:
5/3 0/6
输出样例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
代码:
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
void q1034(void);
void print4(long int a1,long int b1,long int a2,long int b2, char c);
void printfa(long int a,long int b);
void compute(long int a1, long int b1,long int a2,long int b2, char c);
long int gongyue(long int a, long int b);int main(void){
//	while(1)
		q1034();
	return 0;
}void q1034(void){
	long int a1=0,b1=0,a2=0,b2=0;
	scanf("%ld/%ld %ld/%ld",&a1,&b1,&a2,&b2);


	//封装字符串
	print4(a1,b1,a2,b2,'+');
	compute(a1,b1,a2,b2,'+');
	cout<<endl;
	print4(a1,b1,a2,b2,'-');
	compute(a1,b1,a2,b2,'-');
	cout<<endl;
	print4(a1,b1,a2,b2,'*');
	compute(a1,b1,a2,b2,'*');
	cout<<endl;
	print4(a1,b1,a2,b2,'/');
	compute(a1,b1,a2,b2,'/');

}void print4(long int a1,long int b1,long int a2,long int b2, char c){
	printfa(a1,b1);
	cout<<" "<<c<<" ";
	printfa(a2,b2);
	cout<<" = ";
}
void printfa(long int a,long int b){
	if(a%b==0){
		if(a>=0)
			cout<<a/b;
		if(a<0)
			cout<<"("<<a/b<<")";
	}
	else if(a%b!=0){
		if(a>0){
			if(a>b)
				cout<<a/b<<" ";
			cout<<a%b/gongyue(a%b,b)<<"/"<<b/gongyue(a%b,b);
		}
		else{
			cout<<"(-";
			if(-a>b)
				cout<<(-a)/b<<" ";
			cout<<((-a)%b)/gongyue((-a)%b,b)<<"/"<<b/gongyue((-a)%b,b)<<")";
		}
	}
}
void compute(long int a1, long int b1,long int a2,long int b2, char c){
	if(c=='+'){
		printfa(a1*b2+a2*b1,b1*b2);
	}
	if(c=='-')
		printfa(a1*b2-a2*b1,b1*b2);
	if(c=='*')
		printfa(a1*a2,b1*b2);
	if(c=='/'){
		if(a2==0)
			cout<<"Inf";
		else{
			if(a2<0){
				a2 = -a2;
				b2 = -b2;
			}
			printfa(a1*b2,b1*a2);
		}
	}


}
long int gongyue(long int a, long int b){
	long int yu=0;
	long int t=0;
	if(a<b){
		t = a;
		a = b;
		b = t;
	}
	while(1){
		yu = a % b;
		t = b;
		b = yu;
		a = t;
		if(yu==1)
			return b;
		if(yu==0)
			return a;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值