1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include<iostream>
#include<cmath>
using namespace std;
class fraction
{
public:
fraction(): numerator(0), denominator (1){}; //default
fraction (const int& num, const int& denom): numerator(num), denominator(denom) {}; //parametrized constructor
fraction fractionReduction()const;
friend fraction operator * (const fraction& lhs, const fraction& rhs);
friend ostream& operator << (ostream& os, const fraction& rhs);
private:
int numerator;
int denominator;
};
int gcd(const int& num, const int& den);//greatest common denominator;
int main()
{
fraction f1(9,8), f2(2,3), f3(12, 8), f4(202, 303);
cout<<f4*f1;
cout<<f1*f4;
}
int gcd(const int& numerator, const int& denominator)
{
if(denominator == 0)
{
return numerator;
}
else
{
return gcd(denominator, fmod(numerator, denominator));
}
}
fraction fraction::fractionReduction() const //finding and dividing by greatest common multiple
{
fraction temp1;
temp1.numerator = numerator/gcd(numerator, denominator);//division with gcd => no missing remainders
temp1.denominator = denominator/gcd(numerator, denominator);
return temp1;
}
fraction operator * (const fraction& lhs, const fraction& rhs)
{
fraction temp1;
temp1.numerator = (lhs.numerator )* (rhs.numerator);
temp1.denominator = (lhs.denominator ) * (rhs.denominator);
fraction temp2;
temp2.numerator = temp1.numerator/gcd(temp1.numerator, temp1.denominator);
temp2.denominator = temp1.denominator/gcd(temp1.numerator, temp1.denominator);
return temp2;
}
ostream& operator << (ostream& os, const fraction& rhs)
{
if(rhs.numerator == rhs.denominator)
{
os<<1<<"\n";
}
else
{
os<<rhs.numerator<<"/"<<rhs.denominator<<"\n";
}
return os;
}
|