此文件仅供参考,有不完善的地方请告诉我,我将进行完善,谢谢合作!!本程序是实现分数的加减乘除的,对+ - * / 进行了重载
//类的头文件 class fraction { private: int nr; //分子 int dn; //分母 public: fraction input(); fraction operator +(fraction &); fraction operator -(fraction &); fraction operator *(fraction &); fraction operator /(fraction &); void output(); //输出约分后的分数 void output1(); // 输出普通分数 }; //成员函数 #include<iostream.h> #include"fclass.h" fraction fraction::operator+(fraction &a) { fraction g; g.dn=dn*a.dn; g.nr=nr*a.dn+a.nr*dn; return g; } fraction fraction::operator-(fraction &a) { fraction g; g.dn=dn*a.dn; g.nr=nr*a.dn-a.nr*dn; return g; } fraction fraction::operator*(fraction &a) { fraction g; g.dn=dn*a.dn; g.nr=nr*a.nr; return g; } fraction fraction::operator/(fraction &a) { fraction g; g.dn=dn*a.nr; g.nr=nr*a.dn; return g; } fraction fraction::input() { fraction a; cin>>a.nr>>a.dn; return a; } void fraction::output() { int i; if(dn==0) cout<<"error"<<endl; else if(nr%dn==0) cout<<nr/dn<<endl; else { for(i=2;i<=nr||i<=dn;) { if(nr%i==0&&dn%i==0) { nr=nr/i; dn=dn/i; i=2; } else i++; } cout<<nr <<"/"<<dn<<endl; } } void fraction::output1() { cout<<nr<<"/"<<dn; } //主函数 #include<iostream.h> #include"fclass.h" void menu() { cout<<"=================================================="<<endl; cout<<"1-输入2个新的分数,可进行如下运算:"<<endl; cout<<"2-加法"<<endl; cout<<"3-减法"<<endl; cout<<"4-乘法"<<endl; cout<<"5-除法"<<endl; cout<<"6-退出"<<endl; cout<<"=================================================="<<endl; } void main() { void menu(); int m; bool flag=true; fraction s1,s2,s3; while(flag) { menu(); cin>>m; switch(m) { case 1: cout<<"请按照如下方式输入2个分数: 分子/分母"<<endl; s1=s1.input(); s2=s2.input(); cout<<"请输入你要进行的计算:"<<endl; break; case 2: s3=s1+s2; s1.output1(); cout<<" + "; s2.output1(); cout<<"="; s3.output(); break; case 3: s3=s1-s2; s1.output1(); cout<<" - "; s2.output1(); cout<<"="; s3.output(); break; case 4: s3=s1*s2; s1.output1(); cout<<" * "; s2.output1(); cout<<"="; s3.output(); break; case 5: s3=s1/s2; s1.output1(); cout<<" / "; s2.output1(); cout<<"="; s3.output(); break; case 6: flag=false; break; default: break; } } }