fork(6) download
  1. #include <cstdlib>
  2. #include <iostream>
  3. using namespace std;
  4. class Fraction {
  5. private:
  6. int num,den; //числитель и знаменатель
  7. public:
  8. Fraction(){set(0,1);}
  9. Fraction(int n,int d){set(n,d);}
  10. void set (int n,int d) {num=n; den=d;
  11. normalize();}
  12. int get_num() {return num;}
  13. int get_den(){return den;}
  14. Fraction add(Fraction other);
  15. Fraction mult(Fraction other);
  16. private:
  17. void normalize();//преобразов. дроби в стандартн форм
  18. int gcf(int a,int b);//наибольший общий делитель
  19. int lcm(int a,int b);//наименьшее общее кратное
  20. };
  21. int main(){
  22. Fraction f1,f2;
  23. Fraction f3(1,3);
  24. cout<<"The value of f1 is";
  25. cout<<f1.get_num()<<"/";
  26. cout<<f1.get_den()<<endl;
  27. cout<<"The value of f3 is";
  28. cout<<f3.get_num()<<"/";
  29. cout<<f3.get_den()<<endl;
  30. return 0;
  31. }
  32.  
  33. //нормализация : преобразовать дробь к стандартному
  34. //виду ,уникальному для каждого математически отличающегося
  35. //значения
  36. void Fraction::normalize(){
  37. //обработать случаи со значением 0
  38. if(den==0 || num==0){
  39. num=0;
  40. den=1;
  41. }
  42. //оставить отрицательный знак только в числителе.
  43. if(den<0){
  44. num*=-1;
  45. den*=-1;
  46. }
  47. //извлечение наибольшего общего делителя из числителя и
  48. //знаменателя.
  49. int n=gcf(num,den);
  50. num=num/n;
  51. den=den/n;
  52. }
  53. //наибольший общий делитель
  54. int Fraction::gcf(int a,int b){
  55. if(a%b==0)
  56. return abs(b);
  57. else
  58. return gcf(b,a%b);
  59. }
  60. //наименьшее общее кратное
  61. int Fraction::lcm(int a,int b){
  62. return (a/gcf(a,b))*b;
  63. }
  64. Fraction Fraction::add(Fraction other){
  65. Fraction fract;
  66. int lcd=lcm(den,other.den);
  67. int quot1=lcd/den;
  68. int quot2=lcd/other.den;
  69. fract.set(num*quot1+other.num*quot2, lcd);
  70. fract.normalize();
  71. return fract;
  72. }
  73. Fraction Fraction::mult(Fraction other){
  74. Fraction fract;
  75. fract.set(num*other.num, den* other.den);
  76. fract.normalize();
  77. return fract;
  78. }
  79.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
The value of f1 is0/1
The value of f3 is1/3