Advertisement
Guest User

Untitled

a guest
Jan 28th, 2015
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. class Fraction{
  4. public:
  5.     Fraction();
  6.     Fraction(long num, long den);
  7.  
  8.     void setNum(long new_num);
  9.     void setDen(long new_den);
  10.     long getNum();
  11.     long getDen();
  12.  
  13.     void add(Fraction other);
  14.     void sub(Fraction other);
  15.     void mult(Fraction other);
  16.     void div(Fraction other);
  17.     void inc();
  18.     void print();
  19. private:
  20.     long num;
  21.     long den;
  22. };
  23.  
  24. long gcd(long x, long y);
  25.  
  26. Fraction::Fraction():
  27.     num(0),
  28.     den(1)
  29. {
  30. }
  31.  
  32. Fraction::Fraction(long num, long den):
  33.     num(num),
  34.     den(den)
  35. {
  36. }
  37.  
  38. void Fraction::setNum(long new_num)
  39. {
  40.     num = new_num;
  41. }
  42.  
  43. void Fraction::setDen(long new_den)
  44. {
  45.     den = new_den;
  46. }
  47.  
  48. long Fraction::getNum()
  49. {
  50.     return num;
  51. }
  52.  
  53. long Fraction::getDen()
  54. {
  55.     return den;
  56. }
  57.  
  58. void Fraction::add(Fraction other)
  59. {
  60.     num = num * other.den + other.num * den;
  61.     den *= other.den;
  62. }
  63.  
  64. void Fraction::sub(Fraction other)
  65. {
  66.     num = num * other.den - other.num * den;
  67.     den *= other.den;
  68. }
  69.  
  70. void Fraction::mult(Fraction other)
  71. {
  72.     num *= other.num;
  73.     den *= other.den;
  74. }
  75.  
  76. void Fraction::div(Fraction other)
  77. {
  78.     num *= other.den;
  79.     den *= other.num;
  80. }
  81.  
  82. void Fraction::inc()
  83. {
  84.     num += den;
  85. }
  86.  
  87. void Fraction::print()
  88. {
  89.     long divisor = gcd(num, den);
  90.     std::cout << num / divisor << "/" << den / divisor << std::endl;
  91. }
  92.  
  93. long gcd(long x, long y)
  94. {
  95.     return (x == 0) ? y : gcd(y%x, x);
  96. }
  97.  
  98. int main()
  99. {
  100.         Fraction f1, f2, f3, f4, f5, f6, f7;
  101.         f1.setDen(2L);
  102.         f1.setNum(0L);
  103.         f1.print();
  104.         f2.setDen(4L);
  105.         f2.setNum(3L);
  106.         f2.print();
  107.         f3 = f1;
  108.         f3.add(f2);
  109.         f3.print();
  110.         f4 = f1;
  111.         f4.sub(f2);
  112.         f4.print();
  113.         f5 = f1;
  114.         f5.mult(f2);
  115.         f5.print();
  116.         f6;
  117.         f6.div(f2);
  118.         f6.print();
  119.         f7 = f1;
  120.         f7.inc();
  121.         f7.print();
  122. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement