SHOW:
|
|
- or go back to the newest paste.
| 1 | #include <numeric> | |
| 2 | #include <vector> | |
| 3 | #include <iostream> | |
| 4 | ||
| 5 | ||
| 6 | using namespace std; | |
| 7 | ||
| 8 | class Rational {
| |
| 9 | public: | |
| 10 | ||
| 11 | Rational() = default; | |
| 12 | ||
| 13 | Rational(int value){
| |
| 14 | numerator_ = value; | |
| 15 | } | |
| 16 | ||
| 17 | Rational(int numerator, int denominator){
| |
| 18 | if(denominator<0){
| |
| 19 | denominator*=(-1); | |
| 20 | numerator*=(-1); | |
| 21 | } | |
| 22 | int greatest_common_divisor = gcd(numerator, denominator); | |
| 23 | numerator_ = numerator/greatest_common_divisor; | |
| 24 | denominator_ = denominator/greatest_common_divisor; | |
| 25 | } | |
| 26 | ||
| 27 | int Numerator() const {
| |
| 28 | return numerator_; | |
| 29 | } | |
| 30 | ||
| 31 | int Denominator() const {
| |
| 32 | return denominator_; | |
| 33 | } | |
| 34 | ||
| 35 | private: | |
| 36 | int numerator_ = 0; | |
| 37 | int denominator_ = 1; | |
| 38 | }; | |
| 39 | ||
| 40 | Rational Add(Rational r1, Rational r2) {
| |
| 41 | int numerator = r1.Numerator() * r2.Denominator() + r2.Numerator() * r1.Denominator(); | |
| 42 | int denominator = r1.Denominator() * r2.Denominator(); | |
| 43 | // Создаём и возвращаем дробь с заданным числителем и знаменателем | |
| 44 | return Rational{numerator, denominator};
| |
| 45 | } | |
| 46 | ||
| 47 | int main() {
| |
| 48 | Rational zero; // Дробь 0/1 = 0 | |
| 49 | const Rational seven(7); // Дробь 7/1 = 7 | |
| 50 | const Rational one_third(1, 3); // Дробь 1/3 | |
| 51 | vector<Rational> numbers; | |
| 52 | numbers.push_back(Rational{7, 8});
| |
| 53 | // Следующие 2 строки эквивалентны - добавляют в numbers дробь 3/1 | |
| 54 | numbers.push_back(Rational{3});
| |
| 55 | numbers.push_back(3); | |
| 56 | Rational sum = Add(Rational{1,6}, one_third);
| |
| 57 | // Выведет 1/2 | |
| 58 | cout << sum.Numerator() << "/" << sum.Denominator(); | |
| 59 | } |