# PAT Basic 1034

##### 1034 有理数四则运算

``2/3 -4/2``

``````2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)``````

``5/3 0/6``

``````1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf　　题解：这道题看起来蛮复杂的，不过没有啥陷阱，直接写就好了。　　知识点复习：``````
```1 int gcd(int a, int b){
2     if (a%b == 0) {
3         return b;
4     }
5     return gcd(b, a%b);
6 }```

辗转相除法求最大公因数要记牢

``` 1 #include<iostream>
2
3 using namespace std;
4 /*辗转相除法*/
5 int gcd(int a, int b){
6     if (a%b == 0) {
7         return b;
8     }
9     return gcd(b, a%b);
10 }
11 /*输出化简后的数 */
12 void f( long long int a, long long int b){
13     int k = 0, ac = 1, c = 0;
14     if( a == 0){
15         printf("0");
16         return ;
17     }
18     if(a < 0) {
19         ac = 0;
20         a = -a;
21     }
22     if( a/b >= 1){
23         k = a/b;
24         a = a%b;
25         if(!ac) k = -k;
26     }
27     if( a!=0 ){
28         c = gcd(a,b);
29         while( c != 1){
30             a = a/c;
31             b = b/c;
32             c = gcd(a,b);
33         }
34     }
35     if(!ac) printf("(");
36     if(k) printf("%d",k);
37     if(a) {
38         if(k) printf(" ");
39         if(!ac && !k)
40             printf("%lld/%lld",-a,b);
41         else
42             printf("%lld/%lld",a,b);
43     }
44     if(!ac) printf(")");
45 }
46
47 int main()
48 {
49     long long int a1, a2, b1, b2, c1, c2;
50     scanf("%lld/%lld %lld/%lld",&a1,&a2,&b1,&b2);
51     c1 = a1*b2 + a2*b1;
52     c2 = a2*b2;
53     f(a1,a2);
54     printf(" + ");
55     f(b1,b2);
56     printf(" = ");
57     f(c1,c2);
58     printf("\n");
59     c1 = a1*b2 - a2*b1;
60     c2 = a2*b2;
61     f(a1,a2);
62     printf(" - ");
63     f(b1,b2);
64     printf(" = ");
65     f(c1,c2);
66     printf("\n");
67     c1 = a1*b1;
68     c2 = a2*b2;
69     f(a1,a2);
70     printf(" * ");
71     f(b1,b2);
72     printf(" = ");
73     f(c1,c2);
74     printf("\n");
75     c1 = a1*b2;
76     c2 = a2*b1;
77     if( c2 < 0 ){
78         c1 = -c1;
79         c2 = -c2;
80     }
81     f(a1,a2);
82     printf(" / ");
83     f(b1,b2);
84     printf(" = ");
85     if(b1){
86         f(c1,c2);
87     }
88     else cout<<"Inf";
89     return 0;
90 }```

`` ``

PAT Basic 1034

(0)
(0)

0条