Write a Fraction class with following operations: parameterized constructor, addition, subtraction, multiplication and division of 2 fractions
Source code :
#include <iostream>
using namespace std;
class Fraction{
private:
int n, d;
public:
Fraction ()
{
n=1;
d=1;
}
Fraction(int nu, int de)
{
n= nu;
d=de;
}
Fraction addition(Fraction f1)
{
int nu= n*f1.d+f1.n*d;
int de= d*f1.d;
return Fraction(nu/hcf(nu, de), de/hcf(nu, de));
}
Fraction subtraction(Fraction f1)
{
int nu= n*f1.d-f1.n*d;
int de= d*f1.d;
return Fraction(nu/hcf(nu, de), de/hcf(nu, de));
}
Fraction multiply(Fraction f1)
{
int nu= n*f1.n;
int de= d*f1.d;
return Fraction(nu/hcf(nu, de), de/hcf(nu, de));
}
Fraction division(Fraction f1)
{
int nu= n*f1.d;
int de= d*f1.n;
return Fraction(nu/hcf(nu, de), de/hcf(nu, de));
}
int hcf(int nu, int de)
{
int r;
while(de!=0)
{
r= nu%de;
nu=de;
de=r;
}
return nu;
}
void display()
{
cout<<n<<"/"<<d<<endl;
return;
}
};
int main()
{
Fraction a(9,8);
Fraction b(7,4);
Fraction c;
cout<<"The first fraction is:";
a.display();
cout<<endl;
cout<<"The second fraction is: ";
b.display();
cout<<endl;
cout<<"The sum of the two fractions is: ";
c= a.addition(b);
c.display();
cout<<endl;
cout<<"The difference of the two fractions is: ";
c= a.subtraction(b);
c.display();
cout<<endl;
cout<<"The sum of the product fractions is: ";
c= a.multiply(b);
c.display();
cout<<endl;
cout<<"The quotient of the two fractions is: ";
c= a.division(b);
c.display();
cout<<endl;
return 0;
}
0 Comments
Post a Comment