#include <iostream.h>
#include <stdlib.h>
#include <math.h>
class CFraction
{
private:
long num;
long den;
public:
CFraction(int num_val = 0, int den_val = 1);
CFraction &add(const CFraction &r_f);
CFraction &sub(const CFraction &r_f);
CFraction &mul(const CFraction &r_f);
CFraction &div(const CFraction &r_f);
void lowTerms();
void showFraction();
};
CFraction::CFraction(int num_val, int den_val)
{
num = num_val;
den = den_val;
}
CFraction & CFraction::add(const CFraction &r_f)
{
num = num*r_f.den + den*r_f.num;
den = den*r_f.den;
lowTerms();
return *this;
}
CFraction &CFraction::sub(const CFraction &r_f)
{
num = num*r_f.den - den*r_f.num;
den = den*r_f.den;
lowTerms();
return *this;
}
CFraction &CFraction::mul(const CFraction &r_f)
{
num = num*r_f.num;
den = den*r_f.den;
lowTerms();
return *this;
}
CFraction &CFraction::div(const CFraction &r_f)
{
num = num*r_f.den;
den = den*r_f.num;
lowTerms();
return *this;
}
void CFraction::showFraction()
{
long fz, fm;
fz = num;
fm = den;
if (fz*fm < 0)
{
cout << "-";
if (fz < 0)
fz *= -1;
if (fm < 0)
fm *= -1;
}
cout << fz << "/" << fm << endl;
}
void CFraction::lowTerms()
{
long tnum, tden, temp, gcd;
tnum = labs(num);
tden = labs(den);
if (tnum != 0 && tden == 0) //check for n/0
{
cout << "Illegal fraction: division by 0";
exit(1);
}
else if (tnum == 0)
{
num = 0;
den = 1;
return;
}
while (tnum != 0) //找分子和分母的最大公约数
{
if (tnum < tden) //若分子大于分母,则交换
{
temp = tnum;
tnum = tden;
tden = temp;
}
tnum = tnum - tden;
}
gcd = tden;
num = num / gcd;
den = den / gcd;
}
void main()
{
CFraction fs1(2, 3), fs2(1, 2);
fs1.add(fs2);
fs1.showFraction();
fs1.sub(fs2);
fs1.showFraction();
}
4_8.rar_site:www.pudn.com
版权申诉
35 浏览量
2022-09-23
07:51:31
上传
评论
收藏 1KB RAR 举报
alvarocfc
- 粉丝: 105
- 资源: 1万+