小写了一下,,放在LINUX里编译并且运行过了。
代码如下:
#include <stdio.h>
#include <math.h>
#include <sys/types.h>
class CRationalNum
{
public:
int SetRationalNum(int a, int b);
int GetA();
int GetB();
CRationalNum operator+(CRationalNum &rRationNum);
CRationalNum operator-(CRationalNum &rRationNum);
CRationalNum operator*(CRationalNum &rRationNum);
CRationalNum operator/(CRationalNum &rRationNum);
bool operator==(CRationalNum &rRationNum);
void MakeSimple();
private:
int m_a;
int m_b;
};
void CRationalNum::MakeSimple()
{
int k;
int a;
int b;
if (m_a == 0)
return;
if (m_a == m_b)
{
m_a = 1;
m_b = 1;
return;
}
else if (m_a > m_b)
{
a = m_a;
b = m_b;
}
else
{
b = m_a;
a = m_b;
}
do
{
k = a % b;
a = b;
b = k;
}while(k != 0);
k=a;
m_a = m_a / k;
m_b = m_b / k;
return;
}
int CRationalNum::SetRationalNum(int a, int b)
{
if (b == 0)
return -1;
m_a = a;
m_b = b;
MakeSimple();
return 0;
}
int CRationalNum::GetA()
{
return m_a;
}
int CRationalNum::GetB()
{
return m_b;
}
CRationalNum CRationalNum::operator+(CRationalNum &rRationNum)
{
CRationalNum rResult;
//a*d+b*c;分母=b*d
rResult.SetRationalNum(m_a * rRationNum.m_b + m_b * rRationNum.m_a, rRationNum.m_b * m_b);
return rResult;
}
CRationalNum CRationalNum::operator-(CRationalNum &rRationNum)
{
//a*d-b*c;分母=b*d
CRationalNum rResult;
if (m_a * rRationNum.m_b - m_b * rRationNum.m_a == 0)
rResult.SetRationalNum(0, 1);
else
rResult.SetRationalNum(m_a * rRationNum.m_b - m_b * rRationNum.m_a, rRationNum.m_b * m_b);
return rResult;
}
CRationalNum CRationalNum::operator*(CRationalNum &rRationNum)
{
CRationalNum rResult;
rResult.SetRationalNum(m_a * rRationNum.m_a, rRationNum.m_b * m_b);
return rResult;
}
CRationalNum CRationalNum::operator/(CRationalNum &rRationNum)
{
CRationalNum rResult;
rResult.SetRationalNum(m_a * rRationNum.m_b, rRationNum.m_a * m_b);
return rResult;
}
bool CRationalNum::operator==(CRationalNum &rRationNum)
{
if ((m_a == rRationNum.GetA()) && (m_b == rRationNum.GetB()))
return true;
else
return false;
}
int main()
{
CRationalNum rNum1, rNum2, rNum3;
rNum1.SetRationalNum(1, 4);
rNum2.SetRationalNum(1, 4);
rNum3 = rNum1 + rNum2;
printf("rNum3 = rNum1 + rNum2: a=%d, b=%d\n", rNum3.GetA(), rNum3.GetB());
rNum3 = rNum1 - rNum2;
printf("rNum3 = rNum1 + rNum2: a=%d, b=%d\n", rNum3.GetA(), rNum3.GetB());
rNum3 = rNum1 * rNum2;
printf("rNum3 = rNum1 * rNum2: a=%d, b=%d\n", rNum3.GetA(), rNum3.GetB());
rNum3 = rNum1 / rNum2;
printf("rNum3 = rNum1 / rNum2: a=%d, b=%d\n", rNum3.GetA(), rNum3.GetB());
if (rNum1 == rNum2)
printf("rNum1 == rNum2\n");
else
printf("rNum1 != rNum2\n");
return 1;
}
"RationalNum.cpp" 144L, 2664C 已写入
[center@sh-hotel ~]$ g++ -o RationNum RationalNum.cpp
[center@sh-hotel ~]$ ./RationNum
rNum3 = rNum1 + rNum2: a=1, b=2
rNum3 = rNum1 + rNum2: a=0, b=1
rNum3 = rNum1 * rNum2: a=1, b=16
rNum3 = rNum1 / rNum2: a=1, b=1
rNum1 == rNum2
[center@sh-hotel ~]$
温馨提示:内容为网友见解,仅供参考