1 Star 0 Fork 0

CoderQi/cpp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Fraction.cpp 2.90 KB
一键复制 编辑 原始数据 按行查看 历史
CoderQi 提交于 2023-05-07 23:21 +08:00 . Fraction.cpp
#include"Fraction.h"
void Fraction::reduce()
{
//分子小于分母
if (this->m_fz < this->m_fm)
{
for (int i = this->m_fz; i >= 1; i--)
{
if ((this->m_fz % i == 0) && (this->m_fm % i == 0))
{
this->m_fz /= i;
this->m_fm /= i;
}
}
}
//分子大于等于分母
else
{
for (int i = this->m_fm; i >= 1; i--)
{
if ((this->m_fz % i == 0) && (this->m_fm % i == 0))
{
this->m_fz /= i;
this->m_fm /= i;
}
}
}
}
ostream& operator<< (ostream& cout, Fraction f)
{
cout << f.m_fz << "/" << f.m_fm;
return cout;
}
istream& operator>>(istream& cin, Fraction &f)// Q1:???这里为啥加引用才能过去
{
cin >> f.m_fz >> f.m_fm;
return cin;
}
Fraction ::Fraction(int fz,int fm)
{
while (1)
{
if (fm != 0)
{
break;
}
else
{
cout << "输入有误,请重新输入分子和分母" << endl;
cin >> fz >> fm;
}
}
this->m_fz = fz;
this->m_fm = fm;
}
Fraction Fraction::operator+(Fraction&f2)
{
static Fraction f3(0, 1);
f3.m_fz = this->m_fm * f2.m_fz + f2.m_fm * this->m_fz;
f3.m_fm = this->m_fm * f2.m_fm;
return f3;
}
Fraction Fraction::operator-(Fraction& f2)
{
static Fraction f3(0, 1);
f3.m_fz = this->m_fm * f2.m_fz - f2.m_fm * this->m_fz;
f3.m_fm = this->m_fm * f2.m_fm;
return f3;
}
Fraction Fraction::operator*(Fraction& f2)
{
static Fraction f3(0, 1);
f3.m_fz = this->m_fz * f2.m_fz;
f3.m_fm = this->m_fm * f2.m_fm;
return f3;
}
Fraction Fraction::operator/(Fraction& f2)
{
static Fraction f3(0, 1);
f3.m_fz = this->m_fz * f2.m_fm;
f3.m_fm = this->m_fm * f2.m_fz;
return f3;
}
//前置++
Fraction& Fraction::operator++()
{
this->m_fz = this->m_fz + this->m_fm;
return *this; //返回自身,返回类型是 类& 否则会在返回时创建一个新对象
}
//后置++
Fraction Fraction::operator++(int)
{
Fraction temp = *this;
this->m_fz = this->m_fz + this->m_fm;
return temp;
}
//后置--
Fraction Fraction::operator--(int)
{
Fraction temp = *this;
this->m_fz = this->m_fz - this->m_fm;
return temp;
}
//<
bool Fraction::operator<(Fraction& f2)
{
this->m_fz = this->m_fz * f2.m_fm;
f2.m_fz = f2.m_fz * this->m_fm;
if (this->m_fz < f2.m_fz)
{
return true;
}
else
{
return false;
}
}
//>
bool Fraction::operator>(Fraction& f2)
{
this->m_fz = this->m_fz * f2.m_fm;
f2.m_fz = f2.m_fz * this->m_fm;
if (this->m_fz > f2.m_fz)
{
return true;
}
else
{
return false;
}
}
// ==
bool Fraction::operator==(Fraction& f2)
{
this->m_fz = this->m_fz * f2.m_fm;
f2.m_fz = f2.m_fz * this->m_fm;
if (this->m_fz == f2.m_fz)
{
return true;
}
else
{
return false;
}
}
//!=
bool Fraction::operator!=(Fraction& f2)
{
this->m_fz = this->m_fz * f2.m_fm;
f2.m_fz = f2.m_fz * this->m_fm;
if (this->m_fz != f2.m_fz)
{
return true;
}
else
{
return false;
}
}
void Fraction::display()
{
cout << this->m_fz << "/" << this->m_fm << endl;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/programmercg/cpp.git
git@gitee.com:programmercg/cpp.git
programmercg
cpp
cpp
master

搜索帮助