開學以來,各種忙碌,好久沒有刷題了。。。。今天在POJ刷了題,,,很簡單

 

 

分數(shù)加減法
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 8389 Accepted: 2668

Description

編寫一個C程序,實現(xiàn)兩個分數(shù)的加減法

Input

輸入包含多行數(shù)據(jù)
每行數(shù)據(jù)是一個字符串,格式是"a/boc/d"。

其中a, b, c, d是一個0-9的整數(shù)。o是運算符"+"或者"-"。

數(shù)據(jù)以EOF結(jié)束
輸入數(shù)據(jù)保證合法

Output

對于輸入數(shù)據(jù)的每一行輸出兩個分數(shù)的運算結(jié)果。
注意結(jié)果應符合書寫習慣,沒有多余的符號、分子、分母,并且化簡至最簡分數(shù)

Sample Input

1/8+3/8
1/4-1/2
1/3-1/3

Sample Output

1/2
-1/4
0

Source

 

 

#include<stdio.h>
int gcd(int a,int b)
{
if(b==0) return a;
return gcd(b,a%b);
}
int lcm(int a,int b)
{
int c=gcd(a,b);
return a*b/c;
}
int main()
{
int a,b,c,d;
char ch;
while(scanf("%d/%d%c%d/%d",&a,&b,&ch,&c,&d)!=EOF)
{
int m=lcm(b,d);
int n;
if(ch=='+') n=a*(m/b)+c*(m/d);
else n=a*(m/b)-c*(m/d);
if(n==0) printf("0\n");
else
{
int t=gcd(m,n);
n
=n/t;m=m/t;
if(m<0) m=-m,n=-n;
if(m==1) printf("%d\n",n);
else
printf(
"%d/%d\n",n,m);
}
}
return 0;
}

文章來源:http://www.cnblogs.com/kuangbin/archive/2011/09/15/2178096.html