Design a class that performs arithmetic and relational operations on fractions.
QUESTION
Design a class that performs arithmetic and relational operations on fractions. Overload the operations so that appropriate symbols can be used to perform the operation. Also overload the stream insertion and stream extraction operations for easy input and output. Test the following:
Suppose x,y and z are objects if the type fractionType.If the input is 2/3,
cin>>x; should store 2/3 in x.
cout <<x+y<<endl: should output the value of x+y in fraction form.
z = x+y; should store the sum of and y in z in fraction form.
SUMMARY
The fraction class which is implemented has a numerator and a denominator as its members. Some operators are overloaded to perform addition, subtraction, multiplication, or division on the two fractions.
EXPLANATION
The class fraction has n and d as its members representing the numerator and denominator respectively. The operators ‘+’, ‘-‘, ‘*’ and ‘/’ are implemented which adds, subtracts, multiplies, and divides the two fractions. The insertion and extraction operators are overloaded to print the result of a fraction. In the below program we are creating a class that performs arithmetic and relational operations on fractions.
CODE
#include<iostream> using namespace std; #include <string> // class that performs arithmetic and relational operations on fractions class fraction { int n; /* numerator int d; /*denominator public: void operator+(fraction c) { fraction temp; temp.n=(n*c.d)+(c.n*d); temp.d=d*c.d; cout<<"Addition: "<<temp.n<<"/"<<temp.d<<endl; } void operator-(fraction c) { fraction temp; temp.n=(n*c.d)-(c.n*d); temp.d=d*c.d; cout<<"Subtraction: "<<temp.n<<"/"<<temp.d<<endl; } void operator *(fraction c) { fraction temp; temp.n=n*c.n; temp.d=d*c.d; cout<<"Multiplication: "<<temp.n<<"/"<<temp.d<<endl; } void operator/(fraction c) { fraction temp; temp.n= n*c.d; temp.d=c.n*d; cout<<"Division: "<<temp.n<<"/"<<temp.d<<endl; } friend ostream &operator<<(ostream &out, const fraction &f) { out<<f.n<<"/"<<f.d<<endl; return out; } friend istream &operator>>(istream &in, fraction &f) { string st; in>>st; int x=st.find('/'); string st1="",st2=""; for(int i=0;i<x;i++) st1+=st[i]; for(int j=x+1;j<st.length();j++) st2+=st[j]; f.n=stoi(st1); f.d=stoi(s2); return in; } }; int main() { fraction f1,f2; cin>>f1; cin>>f2; fraction f3,f4,f5,f6; f1+f2; f1-f2; f1*f2; f1/f2; }
OUTPUT
3/4
1/4
Addition: 4/4
Subtraction: 2/4
Multiplication: 3/16
Division : 3