我的做法是,直接通分,首先不管有无公因子,也就是把a/b(opt)c/d化成(a*d(opt)c*b)/b*d;然后再分子分母约分就OK了,一开始考虑错了范围,Wa了几次,代码如下:
code
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include <math.h>
5
6int gdb(int a,int b)
7{
8 int tmp,ret;
9 if(a < b)
10 {
11 tmp = a;
12 a = b;
13 b =tmp;
14 }
15 while(b)
16 {
17 tmp = a;
18 a = b;
19 b = tmp%b;
20 }
21 ret = a;
22 return ret;
23}
24int main(void)
25{
26 int a,b,c,d;
27 char opt;
28 int ans_a,ans_b;
29 while(EOF != scanf("%d/%d%c%d/%d",&a,&b,&opt,&c,&d))
30 {
31 if('+' == opt)
32 {
33 ans_b = b*d;
34 ans_a = a*d+b*c;
35 a = gdb(ans_a,ans_b);
36 ans_a /= a;
37 ans_b /= a;
38 }
39 else
40 {
41 ans_b = b*d;
42 ans_a = a*d-b*c;
43 if(ans_a < 0)
44 {
45 a = gdb(-ans_a,ans_b);
46 }
47 else
48 {
49 a = gdb(ans_a,ans_b);
50 }
51 ans_a /= a;
52 ans_b /= a;
53 }
54 if(0 == ans_a)
55 printf("0\n");
56 else
57 {
58 if(ans_a%ans_b == 0)
59 printf("%d\n",ans_a/ans_b);
60 else
61 printf("%d/%d\n",ans_a,ans_b);
62 }
63
64 }
65 return 0;
66}
67