PAT A1088 Rational Arithmetic(C++)

PAT甲级目录 | PAT乙级目录

题目描述

原题地址:A1088 Rational Arithmetic
中文版:B1034 有理数四则运算

解题思路

分情况讨论。

易错点

  • 不用 long int 会溢出
  • 要注意及时化简避免溢出
  • 除法的时候注意符号

也许陌生的知识点

  • long int gcd(long int a, long int b){ return b == 0 ? abs(a) : gcd(b, a % b);}
    • 获取最大公约数的函数,记住就好

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <cstdio>
#include <cmath>
long int gcd(long int a, long int b){ return b == 0 ? abs(a) : gcd(b, a % b);}
void print(long int &a, long int &b){
if(a < 0) printf("(");
long int temp = gcd(a, b);
a /= temp;
b /= temp;
if(a % b == 0) printf("%ld", a/b);
else{
if(a / b != 0) printf("%ld ", a/b);
printf("%ld/%ld", (a / b < 0) ? (- a % b) : a % b , b);
}
if(a < 0) printf(")");
}
int main(){
long int a1, b1, a2, b2, c1, c2;
char op[] = {'+', '-', '*', '/'};
scanf("%ld/%ld %ld/%ld", &a1, &b1, &a2, &b2);
for(int i = 0; i < 4; i++){
print(a1, b1);
printf(" %c ", op[i]);
print(a2, b2);
printf(" = ");
if(i == 0){ // a + b
c1 = a1 * b2 + a2 * b1;
c2 = b1 * b2;
}else if(i == 1){ // a - b
c1 = a1 * b2 - a2 * b1;
c2 = b1 * b2;
}else if(i == 2){ // a * b
c1 = a1 * a2;
c2 = b1 * b2;
}else if(i == 3){ // a / b
if(a2 == 0) printf("Inf");
else{
c1 = a1 * b2;
c2 = abs(b1 * a2);
if(a2 < 0) c1 = - c1;
}
}
if(i !=3 || (i == 3 && a2 != 0) ) print(c1, c2);
printf("\n");
}
return 0;
}