Fractional addition and subtraction (poj00009)
Fractional addition and subtraction
| Time Limit:1000 MS |
|
Memory Limit:65536 K |
| Total Submissions:12564 |
|
Accepted:4194 |
Description
Write a C program to add and subtract two scores
Input
Input contains multiple rows of data
Each row of data is a string in the format of "a/boc/d ".
A, B, c, and d are integers 0-9. O is the operator "+" or "-".
Data ends with EOF
Input data is valid
Output
The calculation result of two scores is output for each row of the input data.
Note that the results should conform to the writing habits, with no redundant symbols, molecules, and denominator, and be simplified to the simplest score.
Sample Input
1/8+3/81/4-1/21/3-1/3
Sample Output
1/2-1/40
#include
#include
#includeusing namespace std;int gcd(int a,int b){return b==0?a:gcd(b,a%b);}int main(){int a,b,c,d,x,y,sum,k,t;char s;while(scanf("%d/%d%c%d/%d",&a,&b,&s,&c,&d)!=EOF){if(s=='+'){x=a*d+b*c;y=b*d;k=x/gcd(x,y);t=y/gcd(x,y);if(t==1)printf("%d\n",k);else{printf("%d/%d\n",k,t);}}else{x=a*d-b*c;y=b*d;if(x==0)printf("0\n");else{k=x/gcd(x,y);t=y/gcd(x,y);if(t==1)printf("%d\n",k);else{if(x>0)printf("%d/%d\n",k,t);elseprintf("%d/%d\n",k*-1,t*-1);}}}}return 0;}