1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

#include<iostream>
#include<conio.h>
using namespace std;
class rational
{
int n,d;
public:
rational() : n(1), d(1) {};
~rational(){};
void getData()
{
cout<<"\nEnter a numerator: ";
cin>>n;
cout<<"Enter a denominator: ";
cin>>d;
cout<<endl;
while(d==0)
{
cout<<"Please enter a denominator: ";
cin>>d;
}
while(d<0)
{
n *= 1;
d *= 1;
}
}
int GCD(int n1, int remainder)
{
if(remainder==0)
return(n1);
else { return(GCD(remainder,n1%remainder)); }
}
void reduce(int &n,int &d)
{
int rdc = 0;
if(d>n)
rdc = GCD(d,n);
else if(d<n)
rdc = GCD(n,d);
else
rdc = GCD(n,d);
n /= rdc;
d /= rdc;
cout<<"\nAfter operating the rational numbers are: "<<n<<"/"<<d<<endl;
}
void operator +(rational c1)
{
rational temp;
temp.n=(n*c1.d)+(c1.n*d);
temp.d=c1.d*d;
reduce(temp.n,temp.d);
}
void operator (rational c1)
{
rational temp;
temp.n=(n*c1.d)(c1.n*c1.d);
temp.d=c1.d*d;
reduce(temp.n,temp.d);
}
void operator *(rational c1)
{
rational temp;
temp.n=n*c1.n;
temp.d=d*c1.d;
reduce(temp.n,temp.d);
}
void operator /(rational c1)
{
rational temp;
temp.n=n*c1.d;
temp.d=d*c1.n;
if(temp.d<0)
{
temp.n *= 1;
temp.d *= 1;
}
reduce(temp.n,temp.d);
}
};
int main()
{
rational c1, c2;
int n;
cout<<"Enter the data for the first fraction: ";
c1.getData();
cout<<"Enter the data for the second fraction: ";
c2.getData ();
cout<<"1 . Addition of the two fractions"<<endl;
cout<<"2 . Subtraction of the two fractions"<<endl;
cout<<"3 . Multiplication of the two fractions"<<endl;
cout<<"4 . Division of the two fractions"<<endl;
cout<<"\nEnter your choice: ";
cin>>n;
switch(n)
{
case 1:
c1+c2;
getch();
break;
case 2:
c1c2;
getch();
break;
case 3:
c1*c2;
getch();
break;
case 4:
c1/c2;
getch();
break;
default:
cout<<"Invalid choice."<<endl;
return 0;
}
getch();
return 0;
}
