Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <cmath>
- #include <iostream>
- #include <map>
- #include <set>
- #include <string>
- #include <utility>
- #include <vector>
- #include <numeric>
- using namespace std;
- /*int gcd(int n, int m) {
- return 2;
- }*/
- class Rational {
- public:
- int Numerator() const {
- return numerator_;
- }
- int Denominator() const {
- return denominator_;
- }
- Rational() {
- Numerator();
- Denominator();
- }
- Rational(int i) {
- SetNum(i);
- SetDen(1);
- }
- Rational(int i, int j) {
- int c=1;
- if (i!=0)
- {
- c = gcd(abs(i),abs(j));
- }
- if (i*j<0) {
- i=-abs(i);
- j=abs(j);
- }
- if (i*j>0){
- i=abs(i);
- j=abs(j);
- }
- // cout<<"***"<<i<<"***"<<j<<"***"<<c<<"***"<<endl;
- SetNum(i/c);
- SetDen(j/c);
- }
- private:
- int numerator_ = 0;
- int denominator_ = 1;
- void SetNum(int num) {
- numerator_ = num;
- }
- void SetDen(int den) {
- denominator_ = den;
- }
- };
- Rational Add(Rational r1, Rational r2) {
- int numerator = r1.Numerator() * r2.Denominator() + r2.Numerator() * r1.Denominator();
- int denominator = r1.Denominator() * r2.Denominator();
- // Создаём и возвращаем дробь с заданным числителем и знаменателем
- return Rational{ numerator, denominator };
- }
- int main() {
- Rational r1;
- Rational r2(8);
- Rational r3(-8);
- Rational r4(1,2);
- Rational r5(-1,2);
- Rational r6(10,-20);
- Rational r7(-1,-2);
- Rational r8(10,15);
- Rational r9(0,-5);
- cout << r1.Numerator() << "/" << r1.Denominator()<<endl;
- cout << r2.Numerator() << "/" << r2.Denominator()<<endl;
- cout << r3.Numerator() << "/" << r3.Denominator()<<endl;
- cout << r4.Numerator() << "/" << r4.Denominator()<<endl;
- cout << r5.Numerator() << "/" << r5.Denominator()<<endl;
- cout << r6.Numerator() << "/" << r6.Denominator()<<endl;
- cout << r7.Numerator() << "/" << r7.Denominator()<<endl;
- cout << r8.Numerator() << "/" << r8.Denominator()<<endl;
- cout << r9.Numerator() << "/" << r9.Denominator()<<endl;
- /* Rational zero; // Дробь 0/1 = 0
- const Rational seven(7); // Дробь 7/1 = 7
- const Rational one_third(1, 3); // Дробь 1/3
- vector<Rational> numbers;
- numbers.push_back(Rational{ 7, 8 });
- // Следующие 2 строки эквивалентны - добавляют в numbers дробь 3/1
- numbers.push_back(Rational{ 3 });
- numbers.push_back(3);
- Rational sum = Add(Rational{ -1,6 }, one_third);
- // Выведет 1/2
- cout << sum.Numerator() << "/" << sum.Denominator();
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement