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; } }