您的位置:首页 > 其它

Pat(Advanced Level)Practice--1088(Rational Arithmetic)

2015-01-09 23:51 344 查看

Pat1088代码

题目描述:

For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.
Input Specification:
Each input file contains one test case, which gives in one line the two rational numbers in the format "a1/b1 a2/b2". The numerators and the denominators are all in the range of
long int. If there is a negative sign, it must appear only in front of the numerator. The denominators are guaranteed to be non-zero numbers.
Output Specification:
For each test case, print in 4 lines the sum, difference, product and quotient of the two rational numbers, respectively. The format of each line is "number1 operator number2 = result". Notice that all the rational numbers must
be in their simplest form "k a/b", where k is the integer part, and
a/b is the simplest fraction part. If the number is negative, it must be included in a pair of parentheses. If the denominator in the division is zero, output "Inf" as the result. It is guaranteed that all the output integers are in the range
of long int.
Sample Input 1:
2/3 -4/2
Sample Output 1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
Sample Input 2:
5/3 0/6
Sample Output 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

AC代码:
#include<cstdio>
#include<cstdlib>

using namespace std;

long Gcd(long a,long b){
long temp;
if(a<0)
a=-a;
if(b<0)
b=-b;
while(b!=0){
temp=a%b;
a=b;
b=temp;
}
return a;
}

void featureNormalize(long *k,long *a,long *b){
long gcd=Gcd(*a,*b);
*a=*a/gcd;
*b=*b/gcd;
if(*a<0){
*a=-*a;
if(*a>=*b){
*k=(*a)/(*b);
*a=(*a)%(*b);
*k=-*k;
}else{
*a=-*a;
*k=0;
}
}else{
if(*a>=*b){
*k=(*a)/(*b);
*a=(*a)%(*b);
}else{
*k=0;
}
}
}

void output(long k,long a,long b){
if(k<0){
printf("(%ld",k);
if(a==0){
printf(")");
}else{
printf(" %ld/%ld)",a,b);
}
}else if(k>0){
if(a>0){
printf("%ld %ld/%ld",k,a,b);
}else if(a==0){
printf("%ld",k);
}
}else{
if(a>0){
printf("%ld/%ld",a,b);
}else if(a==0){
printf("0");
}else{
printf("(%ld/%ld)",a,b);
}
}
}

int main(int argc,char *argv[]){
long a1,b1,a2,b2,a3,b3;
long k1,k2,k3;
long n,m,p,q;
char opt[4]={'+','-','*','/'};
scanf("%ld/%ld %ld/%ld",&a1,&b1,&a2,&b2);
n=a1;
m=b1;
p=a2;
q=b2;
featureNormalize(&k1,&a1,&b1);
featureNormalize(&k2,&a2,&b2);
for(long i=0;i<4;i++){
output(k1,a1,b1);
switch (opt[i]){
case '+':
a3=n*q+p*m;
b3=m*q;
printf(" + ");
break;
case '-':
a3=n*q-p*m;
b3=m*q;
printf(" - ");
break;
case '*':
a3=n*p;
b3=m*q;
printf(" * ");
break;
case '/':
a3=n*q;
b3=m*p;
printf(" / ");
break;
}
output(k2,a2,b2);
printf(" = ");
if(opt[i]=='/'&&b3==0){
printf("Inf\n");
}else{
if(b3<0){
b3=-b3;
a3=-a3;
}
featureNormalize(&k3,&a3,&b3);
output(k3,a3,b3);
printf("\n");
}
}
return 0;
}


注意:用int会有部分case不能通过,所以选用long类型;貌似写得好烂的样子,有时间再优化吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Advance pat