Create a class called Rational for performing arithmetic with rational nos. Use integer variables to represent numerator and denominator. Write a constructer method that enables an object of this class to be initialized when it is declared. Provide a no argument constructor with default values in case no initializes are provided. Provide a copy constructor also. Write methods for
a. Addition, Overload '+' operator
b. Subtraction, Overload '-' operator
c. Multiply, Overload ‘*’ operator
d. Division, Overload '/' operator
e. Increment, Overload ++ operator (both prefix & postfix)
f. Overload operator = = (to check equality of two rational nos.) as a friend function
g. Overload Assignment operator
h. Printing in the form of a/b
#include<iostream>
using namespace std;
class rational
{
int x,y;
public:
rational(int i=1, int j=1)
{
x=i;
y=j;
}
rational operator + (rational ob)
{
rational temp;
temp.x= (x*ob.y + y*ob.x);
temp.y= y*ob.y;
return temp;
}
rational operator - (rational ob)
{
rational temp;
temp.x= (x*ob.y - y*ob.x);
temp.y= y*ob.y;
return temp;
}
rational operator * (rational ob)
{
rational temp;
temp.x= x*ob.x;
temp.y= y*ob.y;
return temp;
}
rational operator / (rational ob)
{
rational temp;
temp.x= x*ob.y;
temp.y= y*ob.x;
return temp;
}
rational operator = (rational ob)
{
x=ob.x;
y=ob.y;
return *this;
}
rational operator ++ () // prefix increment
{
x++;
y++;
return *this;
}
rational operator ++ ( int x) //postfix
{
rational temp = *this;
x++;
y++;
return temp;
}
friend int operator == (rational ob1, rational ob2);
void display()
{
cout<<" x/y ="<<x<<"/"<<y;
}
};
int operator == (rational ob1, rational ob2)
{
if((ob1.x * ob2.y) == (ob2.x * ob1.y)) /* x1 y2 = = x2 y1
-- * -- -- * --
y1 y2 y2 y1 */
return 1;
else
return 0;
}
void main()
{
rational r3;
int x,y;
cout<<" Enter 1st rational number\n x(numerator) = ";
cin>>x;
cout<<" y(denominator) = ";
cin>>y;
rational r1(x,y);
r1.display();
cout<<"\n Enter 2nd rational number\n x(numerator) = ";
cin>>x;
cout<<" y(denominator) = ";
cin>>y;
rational r2(x,y);
r2.display();
r3=r1 + r2;
cout<<"\n\n r3=r1 + r2 \n";
r3.display();
r3=r1 - r2;
cout<<"\n\n r3=r1 - r2 \n";
r3.display();
r3=r1 * r2;
cout<<"\n\n r3=r1 * r2 \n";
r3.display();
r3=r1 / r2;
cout<<"\n\n r3=r1 / r2 \n";
r3.display();
if(r1==r2)
cout<<"\n\n r1 is equal to r2\n\n";
else
cout<<"\n\n r1 is not equal to r2\n\n\n";
r1.display();
cout<<"\n Postfix Increment\n r1++ = ";
r1++; //postfix
r1.display();
cout<<"\n\n\n r2 = ";
r2.display();
++r2; //prefix
cout<<"\n Prefix Increment\n ++r2 = ";
r2.display();
cout<<"\n\n";
system("pause");
}
Comments
Post a Comment