我定义了一个分数类,但不知怎么给分数约分,高手帮忙看一下
#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;
}
------解决方案--------------------
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;
}
===
你上面的程序有一些错误,自己慢慢调去吧呵呵
[解决办法]
可以参考他这个.
http://community.csdn.net/Expert/topic/5482/5482891.xml?temp=.425091