Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. class Rational {
  7. public:
  8. Rational() {
  9. up = 0;
  10. down = 1;
  11. }
  12.  
  13. Rational(int numerator, int denomirator) {
  14. if (numerator != 0) {
  15. if (numerator < 0 && denomirator < 0) {
  16. up = -numerator;
  17. down = -denomirator;
  18. } else if (numerator > 0 && denomirator < 0){
  19. up = -numerator;
  20. down = -denomirator;
  21. } else {
  22. up = numerator;
  23. down = denomirator;
  24. }
  25. } else {
  26. up = 0;
  27. down = 1;
  28. }
  29. Optimize();
  30. }
  31.  
  32. int Numerator() const {
  33. return up;
  34. }
  35.  
  36. int Denominator() const {
  37. return down;
  38. }
  39.  
  40. private:
  41. void Optimize() {
  42. int uni = gcd(up, down);
  43. while (uni != 1) {
  44. up = up / uni;
  45. down = down / uni;
  46. uni = gcd(up, down);
  47. }
  48.  
  49. }
  50.  
  51. static int gcd(int c, int d) {
  52. while (d) {
  53. c %= d;
  54. swap(c, d);
  55. }
  56. return c;
  57. }
  58.  
  59. int up;
  60. int down;
  61. };
  62.  
  63. int main() {
  64.  
  65. Rational r(3, 10);
  66. if (r.Numerator() != 3 || r.Denominator() != 10) {
  67. cout << "Rational(3, 10) != 3/10" << endl;
  68. return 1;
  69. }
  70.  
  71.  
  72. Rational r1(8, 12);
  73. if (r1.Numerator() != 2 || r1.Denominator() != 3) {
  74. cout << "Rational(8, 12) != 2/3" << endl;
  75. return 2;
  76. }
  77.  
  78.  
  79. Rational r2(-4, 6);
  80. if (r2.Numerator() != -2 || r2.Denominator() != 3) {
  81. cout << "Rational(-4, 6) != -2/3" << endl;
  82. return 3;
  83. }
  84.  
  85.  
  86. Rational r3(4, -6);
  87. if (r3.Numerator() != -2 || r3.Denominator() != 3) {
  88. cout << "Rational(4, -6) != -2/3" << endl;
  89. return 3;
  90. }
  91.  
  92.  
  93. Rational r4(0, 15);
  94. if (r4.Numerator() != 0 || r4.Denominator() != 1) {
  95. cout << "Rational(0, 15) != 0/1" << endl;
  96. return 4;
  97. }
  98.  
  99.  
  100. Rational defaultConstructed;
  101. if (defaultConstructed.Numerator() != 0 || defaultConstructed.Denominator() != 1) {
  102. cout << "Rational() != 0/1" << endl;
  103. return 5;
  104. }
  105.  
  106. int x, y;
  107. cin >> x >> y;
  108. Rational custom(x, y);
  109. cout << custom.Numerator() << " " << custom.Denominator() << "\n";
  110.  
  111. cout << "OK" << endl;
  112. return 0;
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement