| 发表于: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; } |
|
|
|
|