C++實現重載分數的四則運算:
#include<iostream>
using namespace std;
class Point
{
private:
int c_point;
int m_point;
char code;
public:
Point()
{
code='/';
}
Point(int n1,int n2)
{
c_point=n1;
m_point=n2;
code='/';
}
void Output()
{
if(m_point==0)cout<<"error";
else
if(m_point==1)cout<<c_point;
else
cout<<"("<<c_point<<code<<m_point<<")";
}
int Big(int n1,int n2) //最大公約數
{
int s=1;
int n=n1,m=n2;
while(s!=0)
{
s=n1%n2;
n1=n2;
n2=s;
}
if(n1!=1&&n%n1==0&&m%n1==0)
return n1;
else
return 0;
}
//int Small_Multiple()
Point operator +(Point b)
{
Point c;
int n1,n2,s=1;
n1=m_point;
n2=b.m_point;
if(n1==n2)
{
c.c_point=c_point+b.c_point;
c.m_point=m_point=b.m_point;
}
else
{
while(s!=0)
{
s=n1%n2;
n1=n2;
n2=s;
}
s=m_point*b.m_point/n1; //最小公倍數
c.m_point=s;
c.c_point=c_point*(s/m_point)+b.c_point*(s/b.m_point);
}
int t;
t=Big(c.c_point,c.m_point);
while(t!=0)
{
c.c_point=c.c_point/t;
c.m_point=c.m_point/t;
t=Big(c.c_point,c.m_point);
}
return c;
}
Point operator -(Point b)
{
Point c;
int n1,n2,s=1;
n1=m_point;
n2=b.m_point;
if(n1==n2)
{
c.c_point=c_point-b.c_point;
c.m_point=m_point=b.m_point;
}
else
{
while(s!=0)
{
s=n1%n2;
n1=n2; //最大公約數
n2=s;
}
s=m_point*b.m_point/n1; //最小公倍數
c.m_point=s;
c.c_point=c_point*(s/m_point)-b.c_point*(s/b.m_point);
}
int t;
t=Big(c.c_point,c.m_point);
while(t!=0)
{
c.c_point=c.c_point/t;
c.m_point=c.m_point/t;
t=Big(c.c_point,c.m_point);
}
return c;
}
Point operator *(Point b)
{
Point c;
c.c_point=c_point*b.c_point;
c.m_point=m_point*b.m_point;
int t;
t=Big(c.c_point,c.m_point);
while(t!=0)
{
c.c_point=c.c_point/t;
c.m_point=c.m_point/t;
t=Big(c.c_point,c.m_point);
}
return c;
}
Point operator /(Point b)
{
Point c;
c.c_point=c_point*b.m_point;
c.m_point=m_point*b.c_point;
int t;
t=Big(c.c_point,c.m_point);
while(t!=0)
{
c.c_point=c.c_point/t;
c.m_point=c.m_point/t;
t=Big(c.c_point,c.m_point);
}
return c;
}
};
int main()
{
int n1,n2,m1,m2;
//char a1,b1;
cout<<"請輸入兩個數的分子,分母分別為:";
//cin>>n1>>a1>>n2>>m1>>b1>>m2;
cin>>n1>>n2>>m1>>m2;
Point a(n1,n2),b(m1,m2);
cout<<"這兩個分數為:";
a.Output();cout<<" ";
b.Output();cout<<endl;
//本來想在這定義一個選擇變量,選擇是要進行那個運算符運算
a.Output();
cout<<"+";
b.Output();
cout<<"=";
Point c;
c=a+b;
c.Output();
cout<<endl;
a.Output();
cout<<"-";
b.Output();
cout<<"=";
c=a-b;
c.Output();
cout<<endl;
a.Output();
cout<<"*";
b.Output();
cout<<"=";
c=a*b;
c.Output();
cout<<endl;
a.Output();
cout<<"/";
b.Output();
cout<<"=";
c=a/b;
c.Output();
cout<<endl;
return 0;
}