Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int NOD(int a, int b) {
- if (a < b) {
- swap(a, b);
- }
- while (a % b != 0) {
- a = a % b;
- swap(a, b);
- }
- return b;
- }
- int nok(int a, int b)
- {
- int max = b;
- for (int i = max; i > 0; i++) {
- if ((i % a == 0) && (i % b == 0)) {
- return i;
- }
- }
- }
- class Rational {
- public:
- Rational(){
- p = 0;
- q = 1;
- }
- Rational(int numerator, int denominator):p(numerator), q(denominator){
- if ((p < 0 && q < 0) || q < 0) {
- p *= -1;
- q *= -1;
- }
- if (p == 0) {
- q = 1;
- }
- else {
- int t = NOD(p, q);
- if (t != 1) {
- p /= t;
- q /= t;
- }
- }
- }
- int Numerator() const {
- return p;
- }
- int Denominator() const {
- return q;
- }
- bool operator == (Rational& b) {
- return (Denominator() == b.Denominator() && Numerator() == b.Numerator());
- }
- Rational operator + (Rational& b) {
- int t = nok(Denominator(), b.Denominator());
- int q = t;
- int p = t / Denominator() * Numerator() + t / b.Denominator() * b.Numerator();
- Rational R(p, q);
- return R;
- }
- Rational operator - (Rational& b) {
- int t = nok(Denominator(), b.Denominator());
- int q = t;
- int p = t / Denominator() * Numerator() - t / b.Denominator() * b.Numerator();
- Rational R(p, q);
- return R;
- }
- private:
- int p;
- int q;
- };
- int main() {
- {
- Rational r1(4, 6);
- Rational r2(2, 3);
- bool equal = r1 == r2;
- if (!equal) {
- cout << "4/6 != 2/3" << endl;
- return 1;
- }
- }
- {
- Rational a(2, 3);
- Rational b(4, 3);
- Rational c = a + b;
- bool equal = c == Rational(2, 1);
- if (!equal) {
- cout << "2/3 + 4/3 != 2" << endl;
- return 2;
- }
- }
- {
- Rational a(5, 7);
- Rational b(2, 9);
- Rational c = a - b;
- bool equal = c == Rational(31, 63);
- if (!equal) {
- cout << "5/7 - 2/9 != 31/63" << endl;
- return 3;
- }
- }
- cout << "OK" << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement