C++实现重载分数的四则运算

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;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/d4d2fb268a7464893773f22df9850dda.html