Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdlib>
- #include <iostream>
- #include <string>
- #include <sstream>
- using namespace std;
- class fraction
- {
- private:
- long num;
- long den;
- char over;
- public:
- void getFrac()
- {
- cout << "Enter a fraction: ";
- cin >> num >> over >> den;
- lowterms();
- }
- fraction addFraction(fraction f2)
- {
- f2.num =(num * f2.den) + (den * f2.num);
- f2.den = (den * f2.den);
- return f2;
- }
- fraction subFraction(fraction f2)
- {
- f2.num =(num * f2.den) - (den * f2.num);
- f2.den = (den * f2.den);
- return f2;
- }
- fraction mulFraction(fraction f2)
- {
- f2.num =(num * f2.num);
- f2.den = (den * f2.den);
- return f2;
- }
- fraction divFraction(fraction f2)
- {
- f2.num =(num * f2.den);
- f2.den = (den * f2.num);
- return f2;
- }
- void fraction::lowterms()
- {
- long tnum, tden, temp, gcd;
- tnum = labs(num);
- tden = labs(den);
- if (tden == 0)
- {
- cout<<"Division by 0 is not allowed";exit(3);
- }
- else if (tnum == 0)
- { num = 0; den = 1; return; }
- while(tnum != 0)
- {
- if (tnum < tden)
- { temp = tnum; tnum = tden; tden = temp; }
- tnum = tnum - tden;
- }
- gcd = tden;
- num = num / gcd;
- den = den / gcd;
- }
- void showFrac() const
- {
- cout << "The result is " << num << "/" << den << endl;
- }
- bool equals(fraction f2)
- {
- if (num == f2.num && den == f2.den)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- string toString()
- {
- ostringstream s;
- if(den == 1)
- {
- s << num;
- }
- else
- {
- s << num << over << den;
- }
- return s.str();
- }
- };
- int main()
- {
- fraction f1, f2, f3, f4, f5, f6;
- cout << "This will show the sum, difference, product and quotient of two fractions.\n " << endl;
- f1.getFrac();
- f2.getFrac();
- f3 = f1.addFraction(f2);
- f3.lowterms();
- f3.showFrac();
- f4 = f1.subFraction(f2);
- f4.lowterms();
- f4.showFrac();
- f5 = f1.mulFraction(f2);
- f5.lowterms();
- f5.showFrac();
- f6 = f1.divFraction(f2);
- f6.lowterms();
- f6.showFrac();
- if(f1.equals(f2))
- {
- cout<<"Fractions are equal"<<endl;
- }
- else if(!f1.equals(f2))
- {
- cout<<"Fractions are not equal"<<endl;
- }
- cout<<"First fraction is "<<f1.toString()<<endl;
- cout<<"Second fraction is "<<f2.toString();
- system("pause>0");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement