Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef FRACTION
- #define FRACTION
- class Fraction
- {
- private:
- int num;
- int den;
- public:
- void setFraction(int n, int d);
- Fraction add(const Fraction &f);
- Fraction sub(const Fraction &f);
- Fraction mult(const Fraction &f);
- Fraction div(const Fraction &f);
- void printFraction();
- //Constructors
- Fraction();
- Fraction(int num, int den);
- Fraction(std::string s);
- };
- #endif
- #include "Fraction.h"
- #include <iostream>
- #include <string>
- using namespace std;
- void Fraction::setFraction(int n, int d)
- {
- this->num = n;
- this->den = d;
- }
- Fraction Fraction::add(const Fraction &f)
- {
- Fraction temp;
- temp.num = (this->num * f.den) + (f.num * this->den);
- temp.den = (f.den * this->den);
- return temp;
- }
- Fraction Fraction::sub(const Fraction &f)
- {
- Fraction temp;
- temp.num = (this->num * f.den) - (f.num * this->den);
- temp.den = (f.den * this->den);
- if (temp.den < 0)
- temp.den *= -1;
- return temp;
- }
- Fraction Fraction::mult(const Fraction &f)
- {
- Fraction temp;
- temp.num = this->num * f.num;
- temp.den = this->den * f.den;
- return temp;
- }
- Fraction Fraction::div(const Fraction &f)
- {
- Fraction temp;
- temp.num = this->den * f.num;
- temp.den = this->num * f.den;
- return temp;
- }
- void Fraction::printFraction()
- {
- cout << this->num << "/" << this->den;
- }
- //constructors
- Fraction::Fraction()
- {
- this->setFraction(1, 1);
- }
- Fraction::Fraction(int num, int den)
- {
- this->setFraction(num, den);
- }
- Fraction::Fraction(string s)
- {
- int numerator = 1;
- int denominator = 1;
- for (int i = 0; i < s.length(); i++)
- {
- if (s.at(i) == ' ')
- {
- numerator = stoi(s.substr(0, i));
- denominator = stoi(s.substr(i+1, s.length() - (1 + i)));
- }
- }
- setFraction(numerator, denominator);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement