Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- using namespace std;
- class Rational {
- public:
- Rational() {
- up = 0;
- down = 1;
- }
- Rational(int numerator, int denomirator) {
- if (numerator != 0) {
- if (numerator < 0 && denomirator < 0) {
- up = -numerator;
- down = -denomirator;
- } else if (numerator > 0 && denomirator < 0){
- up = -numerator;
- down = -denomirator;
- } else {
- up = numerator;
- down = denomirator;
- }
- } else {
- up = 0;
- down = 1;
- }
- Optimize();
- }
- int Numerator() const {
- return up;
- }
- int Denominator() const {
- return down;
- }
- private:
- void Optimize() {
- int uni = gcd(up, down);
- while (uni != 1) {
- up = up / uni;
- down = down / uni;
- uni = gcd(up, down);
- }
- }
- static int gcd(int c, int d) {
- while (d) {
- c %= d;
- swap(c, d);
- }
- return c;
- }
- int up;
- int down;
- };
- int main() {
- {
- const Rational r(3, 10);
- if (r.Numerator() != 3 || r.Denominator() != 10) {
- cout << "Rational(3, 10) != 3/10" << endl;
- return 1;
- }
- }
- {
- const Rational r(8, 12);
- if (r.Numerator() != 2 || r.Denominator() != 3) {
- cout << "Rational(8, 12) != 2/3" << endl;
- return 2;
- }
- }
- {
- const Rational r(-4, 6);
- if (r.Numerator() != -2 || r.Denominator() != 3) {
- cout << "Rational(-4, 6) != -2/3" << endl;
- return 3;
- }
- }
- {
- const Rational r(4, -6);
- if (r.Numerator() != -2 || r.Denominator() != 3) {
- cout << "Rational(4, -6) != -2/3" << endl;
- return 3;
- }
- }
- {
- const Rational r(0, 15);
- if (r.Numerator() != 0 || r.Denominator() != 1) {
- cout << "Rational(0, 15) != 0/1" << endl;
- return 4;
- }
- }
- {
- const Rational defaultConstructed;
- if (defaultConstructed.Numerator() != 0 || defaultConstructed.Denominator() != 1) {
- cout << "Rational() != 0/1" << endl;
- return 5;
- }
- }
- cout << "OK" << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement