#include <iostream>
#include <sstream>
#include <string>
#include "fraction.h"
#include "common.h"
using namespace std;
ostream
& operator<<(ostream
& cout,fraction
& x
) //xuat phan so{
if (x.
ms != 1) cout<<'|' <<x.
ms; }
istream
& operator>>(istream
& cin,fraction
& x
) //nhap phan so{
string s;
if ( s[0] != '-' ) x.stof(s,false);
else
{
string s1(s,1,s.size()-1);
x.stof(s1,true);
}
}
fraction fraction::operator~() //rut gon
{
int tmp = gcd(ts,ms);
ts /= tmp;
ms /= tmp;
return *this;
}
fraction fraction::operator-() //so doi
{
ts = -ts;
return *this;
}
fraction fraction::operator*() //nghich dao
{
swap(ts,ms);
return *this;
}
fraction fraction::operator+(fraction x)
{
return ~fraction(ts * x.ms + ms * x.ts,ms * x.ms);
}
fraction fraction::operator-(fraction x)
{
x = -x;
return ~(*this + x);
}
fraction fraction::operator*(fraction x)
{
return ~fraction(ts * x.ts,ms * x.ms);
}
fraction fraction::operator/(fraction x)
{
x = *x;
return ~(*this * x);
}
string its(int value) //int to string
{
ostringstream os;
os <<value;
return os.str();
}
int sti(const string &str) //string to int
{
istringstream is(str);
int i;
is >>i;
return i;
}
string fraction::ftos() //fraction to string
{
string s = its(ts) + '|' + its(ms);
return s;
}
bool isfrac(string& s) //kiem tra la phan so thuc su
{
int i = 0;
while ( (i < s.size()) && (s[i] != '|') ) ++i;
if (i < s.size()) return true;
else return false;
}
void fraction::stof(string& s,bool neg) //string to fraction
{
if (!isfrac(s))
{
ts = sti(s);
ms = 1;
}
else
{
int i = 0;
int pos = i;
int len = 1;
while ( s[i++] != '|' ) ++len;
string num;
num.assign(s,pos,len);
ts = sti(num);
if (neg) ts = -ts;
pos = i;
len = 1;
while ( i < s.size() )
{
++len;
++i;
}
num.assign(s,pos,len);
ms = sti(num);
}
}
void cong(fraction& a,fraction& b)
{
<<"a|b + c|d = (ad + bc)|bd\n"
<<a <<" + " <<b <<"\n=("
<<a.ts <<" * " <<b.ms
<<" + "
<<a.ms <<" * " <<b.ts
<<") | ("
<<a.ms <<" * " <<b.ms
<<")\n=("
<<a.ts*b.ms <<" + " <<a.ms*b.ts
<<") | "
<<a.ms*b.ms
<<"\n="
<<a.ts*b.ms+a.ms*b.ts
<<"|"
<<a.ms*b.ms
<<"\nKet qua: ";
fraction c = a+b;
}
void tru(fraction& a,fraction& b)
{
cout <<"Phep tru\na|b + c|d = (ad + bc)|bd\n" <<a <<" - " <<b <<"\n=("
<<a.ts <<" * " <<b.ms
<<" - "
<<a.ms <<" * " <<b.ts
<<") | ("
<<a.ms <<" * " <<b.ms
<<")\n=("
<<a.ts*b.ms <<" - " <<a.ms*b.ts
<<") | "
<<a.ms*b.ms
<<"\n="
<<a.ts*b.ms-a.ms*b.ts
<<"|"
<<a.ms*b.ms
<<"\nKet qua: ";
fraction c = a-b;
}
void nhan(fraction& a,fraction& b)
{
<<"a|b * c|d = (a * c)|(b * d)\n"
<<a <<" * " <<b <<"\n=("
<<a.ts <<" * " <<b.ts
<<") | ("
<<a.ms <<" * " <<b.ms
<<")\n="
<<a.ts*b.ts <<"|" <<a.ms*b.ms
<<"\nKet qua: ";
fraction c = a*b;
}
void chia(fraction& a,fraction& b)
{
<<"a|b / c|d = a|b * d|c = (a * d)|(b * c)\n"
<<a <<" / " <<b <<"\n=("
<<a.ts <<" * " <<b.ms
<<") | ("
<<a.ms <<" * " <<b.ts
<<")\n="
<<a.ts*b.ms <<"|" <<a.ms*b.ts
<<"\nKet qua: ";
fraction c = a/b;
}