Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Rational {
- public:
- Rational() {
- // Реализуйте конструктор по умолчанию
- numer = 0;
- denom = 1;
- }
- Rational(int a, int b) {
- // Реализуйте конструктор
- int numerator, denominator, nod;
- numerator = a;
- denominator = b;
- a = abs(numerator);
- b = abs(denominator);
- while (a > 0 && b > 0) {
- if (a > b) {
- a %= b;
- }
- else {
- b %= a;
- }
- }
- nod = a + b;
- numer = numerator / nod;
- denom = denominator / nod;
- if (numer*denom < 0) {
- if (denom < 0)
- denom *= (-1);
- if (numer >= 0) {
- numer *= (-1);
- }
- }
- else {
- if (numer < 0) {
- numer *= (-1);
- }
- if (denom < 0) {
- denom *= (-1);
- }
- }
- }
- int Numerator() const {
- return numer;
- }
- int Denominator() const {
- return denom;
- }
- private:
- // Добавьте поля
- int numer;
- int denom;
- };
- Rational operator+ ( Rational & left, Rational& right) {
- int denom_1, numer_1;
- denom_1 = left.Denominator()*right.Denominator();
- numer_1 = right.Numerator()*left.Denominator()+ right.Denominator()*left.Numerator();
- Rational answer(numer_1, denom_1);
- return answer;
- }
- Rational operator- (Rational & left, Rational& right) {
- int denom_1, numer_1;
- denom_1 = left.Denominator()*right.Denominator();
- numer_1 = left.Numerator()*right.Denominator() -right.Numerator()*left.Denominator();
- Rational answer(numer_1, denom_1);
- return answer;
- }
- bool operator== ( const Rational& left,const Rational& right) {//left<right
- if ((left.Numerator() == right.Numerator()) && (left.Denominator() == right.Denominator())) {
- return true;
- }
- return false;
- }
- void printrational(const Rational & rational) {
- cout << rational.Numerator() << "/" << rational.Denominator()<<endl;
- }
- // Реализуйте для класса Rational операторы ==, + и -
- 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;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement