您的位置:程序门 -> c/c++ -> c++ 语言



我定义了一个分数类,但不知怎么给分数约分,高手帮忙看一下


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


我定义了一个分数类,但不知怎么给分数约分,高手帮忙看一下[已结贴,结贴人:mql007]
发表于:2007-04-22 12:37:48 楼主
#include <iostream.h>
class   fraction
{public:
        fraction()
{a=1;b=1;}
fraction(int   am,int   bm)
{a=am;b=bm;}
friend   fraction   operator   +(fraction   m1,fraction   m2);
        friend   fraction   operator   -(fraction   m1,fraction   m2);
friend   fraction   operator   *(fraction   m1,fraction   m2);
friend   fraction   operator   /(fraction   m1,fraction   m2);  
void   show()
{cout < <a < < "/ " < <b < <endl;}
  private:
        int   a,b;
};
fraction   operator   +(fraction   m1,fraction   m2)
{fraction   temp;
  temp.a=m1.a*m2.b+m1.b*m2.b;
  temp.b=m1.b*m2.b;
  return   temp;
}
fraction   operator   -(fraction   m1,fraction   m2)
{fraction   temp;
  temp.a=m1.a*m2.b-m1.b*m2.a;
  temp.b=m1.b*m2.b;
  return   temp;
}
fraction   operator   *(fraction   m1,fraction   m2)
{fraction   temp;
  temp.a=m1.a*m2.a;
  temp.b=m1.b*m2.b;
  return   temp;
}
fraction   operator   /(fraction   m1,fraction   m2)
{fraction   temp;
  temp.a=m1.a*m2.b;
  temp.b=m2.a*m1.b;
  return   temp;
}
void   main   ()
{cout < < "                                                       说明 " < <endl;
  cout < < "此程序用于计算分数的四则运算,用户可根据程序提示,输入分数及运算类型,注意要先输分子再输分母,输完分子后按enter再输分母,分母不得为0,否则程序将退出. " < <endl;
  char   op,p;                           //op用于告诉程序运算类型//
  int   am,bm,an,bn;           //am   an代表分子,bm   bn代表分母//
  cout < < "输入运算类型 " < <endl;
  cin> > op;
  cout < < "输入第一个分数 " < <endl;
  cin> > am> > p> > bm;
  cout < < "输入第二个分数 " < <endl;
  cin> > an> > p> > bn;
  fraction   m1(am,bm),m2(an,bn),m3;
  switch(op)
  {case   '+ ':{m3=m1+m2;cout < <am < < "/ " < <bm < < "   +   " < <an < < "/ " < <bn < < "= ";m3.show();};break;
    case   '- ':{m3=m1-m2;cout < <am < < "/ " < <bm < < "   -   " < <an < < "/ " < <bn < < "= ";m3.show();};break;
    case   '* ':{m3=m1*m2;cout < <am < < "/ " < <bm < < "   *   " < <an < < "/ " < <bn < < "= ";m3.show();};break;
    case   '/ ':{m3=m1/m2;cout < <am < < "/ " < <bm < < "   /   " < <an < < "/ " < <bn < < "= ";m3.show();};break;
    default:cout < < "输入有误,程序结束. " < <endl;
  }
  cout < <endl;

}
发表于:2007-04-22 14:06:071楼 得分:0
自己顶一下
发表于:2007-04-22 14:06:282楼 得分:0
我再顶
发表于:2007-04-22 14:17:133楼 得分:15
int   check(int   m,   int   n)     //返回m,n的最大公约数
{
m   =   abs(m);
n   =   abs(n);
return   check2(m   >   n   ?   m   :   n,   m   <=   n   ?   m   :   n);
}
int   check2(int   max,   int   min)
{
int   mo   =   max   %   min;
if   (mo   ==   0)   {
return   min;
  }
  else   {
  return   check2(min,   mo);
}
}

然后
void   show()
{
int   c   =   check(a,   b);
cout < <a   /   c < < "/ " < <b   /   c < <endl;
}

===
你上面的程序有一些错误,自己慢慢调去吧呵呵
发表于:2007-04-22 14:28:204楼 得分:5
可以参考他这个.
http://community.csdn.net/expert/topic/5482/5482891.xml?temp=.425091
发表于:2007-04-25 18:33:195楼 得分:0
crazy   我怎么给你加分啊     我不会加呀


快速检索

最新资讯
热门点击