1、分数类实现分数之间的加减乘除运算并且结果是约分过后的最简答案程序代码和解释:#includeusing namespace std;int yueshu(int a,int b)/求两个整数最大公约数的函数声明int d = a % b;while(d != 0) a = b;b = d;d = a % b; return b; class fraction/分数类声明public:/外部接口fraction(double z=0.0,double m=0.0)/构造函数 fz=z ; fm=m ; friend fraction operator + (fraction c1,fractio
2、n c2);/运算符 + 重载成员函数friend fraction operator - (fraction c1,fraction c2);/运算符 - 重载成员函数friend fraction operator * (fraction c1,fraction c2);/运算符 * 重载成员函数friend fraction operator / (fraction c1,fraction c2);/运算符 / 重载成员函数void input();/输入分数void output();/输出分数private:/私有数据成员double fz;/分子double fm;/分母;void
3、 fraction:input()/输入函数类外实现coutfzfm;void fraction:output()/输出函数类外实现int a=(int)fz;/将 fz 由 double 型强制类型转换为 int 型int b=(int)fm;/将 fm 由 double 型强制类型转换为 int 型/强制类型转换的原因是; 函数 yueshu()的两个参数都是 int 型的int c=yueshu(a,b);/求分数分子和分母的最大公约数a/=c; b/=c;/化简分子分母if(a=0) /当分子是 0 时,输出分数值为 0 cout“t0“endl; else if(a=b)/当分子=分
4、母时,输出分数值为 1 cout“t1“endl; else if(b=0)/当分母0 时,输出分数的符号移至分数开头 cout“t“(-1)*a“/“(-1)*bendl; else/无上述情况时,正常输出分数值 cout“t“a“/“bendl; fraction operator + (fraction c1,fraction c2) return fraction(c1.fz*c2.fm+c1.fm*c2.fz,c1.fm*c2.fm); fraction operator - (fraction c1,fraction c2) return fraction(c1.fz*c2.fm-
5、c1.fm*c2.fz,c1.fm*c2.fm); fraction operator * (fraction c1,fraction c2) return fraction(c1.fz*c2.fz,c1.fm*c2.fm); fraction operator / (fraction c1,fraction c2) return fraction(c1.fz*c2.fm,c1.fm*c2.fz); int main()while(1)/while(1) 为实现分数计算的不断输入fraction c1,c2,c3;c1.input(); c2.input();cout“输入的两个分数为:“endl;cout“c1=“; c1.output();cout“c2=“; c2.output();cout“两个分数之间能进行所有运算有:“endl;c3=c2+c1;cout“c3 = c2 + c1 = “; c3.output();c3=c2-c1;cout“c3 = c2 - c1 = “; c3.output();c3=c2*c1;cout“c3 = c2 * c1 = “; c3.output();c3=c2/c1;cout“c3 = c2 / c1 = “; c3.output();coutendlendl;程序运行结果: