Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 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. const 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. {
  73. const Rational r(8, 12);
  74. if (r.Numerator() != 2 || r.Denominator() != 3) {
  75. cout << "Rational(8, 12) != 2/3" << endl;
  76. return 2;
  77. }
  78. }
  79.  
  80. {
  81. const Rational r(-4, 6);
  82. if (r.Numerator() != -2 || r.Denominator() != 3) {
  83. cout << "Rational(-4, 6) != -2/3" << endl;
  84. return 3;
  85. }
  86. }
  87.  
  88. {
  89. const Rational r(4, -6);
  90. if (r.Numerator() != -2 || r.Denominator() != 3) {
  91. cout << "Rational(4, -6) != -2/3" << endl;
  92. return 3;
  93. }
  94. }
  95.  
  96. {
  97. const Rational r(0, 15);
  98. if (r.Numerator() != 0 || r.Denominator() != 1) {
  99. cout << "Rational(0, 15) != 0/1" << endl;
  100. return 4;
  101. }
  102. }
  103.  
  104. {
  105. const Rational defaultConstructed;
  106. if (defaultConstructed.Numerator() != 0 || defaultConstructed.Denominator() != 1) {
  107. cout << "Rational() != 0/1" << endl;
  108. return 5;
  109. }
  110. }
  111.  
  112. cout << "OK" << endl;
  113. return 0;
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement