avatar

有理数类

目前支持的功能:

  1. 初始赋值(整形/构造函数)
  2. 四则运算
  3. 输出

就这么点(

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
47
48
49
50
51
52
53
54
#include<bits/stdc++.h>
using namespace std;

class rational {
private:
int a, b;
inline int gcd(int x, int y) { return y? gcd(y, x % y) : x; }
inline rational simplify(rational &x) {
if(b < 0) a = -a, b = -b;
int v = gcd(x.a, x.b);
x.a /= v, x.b /= v;
return x;
}
public:
rational (int x = 0, int y = 1): a(x), b(y) { *this = simplify(*this); }
const rational operator +(rational x) {
rational res;
res.a = a * x.b + b * x.a;
res.b = b * x.b;
return simplify(res);
}
const rational operator -(rational x) {
x.a = -x.a;
return *this + x;
}
const rational operator *(rational x) {
x.a *= a, x.b *= b;
return simplify(x);
}
const rational operator /(rational x) {
a *= x.b, b *= x.a;
return simplify(*this);
}
inline void print() {
simplify(*this);
if(a == 0) cout << 0;
else if(b == 1) cout << a;
else cout << a << "/" << b;
}
};

// 注意事项:
// 目前'='初值只能赋整数,若要赋值为浮点数请使用构造函数
// 输出不支持流,请使用oo.print();

int main() {
rational a = rational(10, 10), b = 2, c;
cout << "a = "; a.print(); cout << ", b = "; b.print(); cout << endl;
cout << "a + b = "; c = a + b; c.print(); cout << endl;
cout << "a - b = "; c = a - b; c.print(); cout << endl;
cout << "a * b = "; c = a * b; c.print(); cout << endl;
cout << "a / b = "; c = a / b; c.print(); cout << endl;
return 0;
}
文章作者: SocialZxy
文章链接: http://socialzxy.github.io/2020/04/04/%E6%9C%89%E7%90%86%E6%95%B0%E7%B1%BB/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 SocialZxy's Blog

评论