include iostream include string using namespace std struct Ratio Ratio

 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
#include <iostream>
#include <string>
using namespace std;
struct Ratio {
Ratio(int num, int denum) : numerator(num), denumerator(denum){ }
Ratio operator+(Ratio op) {
if (op.denumerator == this->denumerator)
return Ratio(numerator+op.numerator, denumerator);
else
return Ratio(numerator*op.denumerator+op.numerator*denumerator, denumerator*op.denumerator);
}
Ratio operator-(Ratio op) {
if (op.denumerator == this->denumerator)
return Ratio(numerator-op.numerator, denumerator);
else
return Ratio(numerator*op.denumerator-op.numerator*denumerator, denumerator*op.denumerator);
}
Ratio operator*(Ratio op) {
return Ratio(numerator*op.numerator, denumerator*op.denumerator);
}
Ratio operator/(Ratio op) {
return Ratio(numerator*op.denumerator, denumerator*op.numerator);
}
string toString() {
return to_string(numerator)+"/"+to_string(denumerator);
}
int numerator; // числитель
int denumerator; // знаменатель
};
int main()
{
Ratio a(2, 5), b(1, 3);
cout << "A: " << a.numerator << " / " << a.denumerator << endl;
cout << "B: " << b.numerator << " / " << b.denumerator << endl;
cout << "A + B: " << (a+b).toString() << endl;
cout << "A - B: " << (a-b).toString() << endl;
cout << "A * B: " << (a*b).toString() << endl;
cout << "A / B: " << (a/b).toString() << endl;
return 0;
}