#include "fraction.h"
#include <math.h>
Fraction::Fraction()
{
top = 0;
bottom = 1;
}
Fraction::Fraction(int a)
{
top = a;
bottom = 1;
}
Fraction::Fraction(int a, int b)
{
top = a;
bottom = b;
normalize();
}
void Fraction::normalize()
{
int a =top;
int b = bottom;
if (top*bottom == 0) return;
int sign = 1;
if(a*b < 0) sign = -1;
int A = abs(a);
int B = abs(b);
int temp;
// get the greatest common denominator
if(A < B){
temp = A;
A = B;
B = temp;
}
while(A%B != 0){
temp = A%B;
A = B;
B = temp;
}
top = sign *abs(a) /B;
bottom = abs(b) / B;
}
Fraction::~Fraction()
{
//dtor
}
Fraction Fraction::operator +(Fraction & frac)
{
int a1 = frac.gettop();
int b1 = frac.getbottom();
return Fraction(this->top*b1+ this->bottom*a1, b1*this->bottom);
}
Fraction Fraction::operator -(Fraction & frac)
{
int a1 = frac.gettop();
int b1 = frac.getbottom();
return Fraction(this->top*b1 - this->bottom* a1, b1*this->bottom);
}
Fraction Fraction::operator *(Fraction & frac)
{
int a1 = frac.gettop();
int b1 = frac.getbottom();
return Fraction(this->top* a1, b1 *this->bottom);
}
Fraction Fraction::operator /(Fraction & frac)
{
int a1 = frac.gettop();
int b1 = frac.getbottom();
return Fraction(this->top * b1 , a1*this->bottom);
}
std::ostream& operator<<(std::ostream & os , const Fraction &F )
{
if (F.bottom == 1) os <<F.top;
else
os << F.gettop() <<"/" << F.getbottom();
return os;
}
std::istream& operator >>(std::istream & os , Fraction &F )
{
int a, b;
char c;
os >> a>>c>> b;
F.top = a;
F.bottom = b;
F.normalize();
return os;
}
double Fraction::toDouble() const
{
return (top+0.0)/ bottom;
}
c++写的分数类,可进行运算操作和比较操作及和浮点数据的转换操作
需积分: 50 15 浏览量
2019-03-18
21:51:54
上传
评论
收藏 1KB ZIP 举报
普通网友
- 粉丝: 0
- 资源: 5