#include <math.h>
#include <stdlib.h>
#include <iostream.h>
//using namespace std;
class fraction
{
public:
fraction(int x=0,int y=1);
void print(); //以“/”的分数形式输出
//定义重载运算符的友元函数
friend fraction operator+(fraction &a,fraction &b);
friend fraction operator-(fraction &a,fraction &b);
friend fraction operator*(fraction &a,fraction &b);
friend fraction operator/(fraction &a,fraction &b);
private:
int numerator,denominator;
//numerator为分子,denominator为分母
void optim();//
化简的函数
};
void fraction::optim()
{
int gcd,min,max;
if(denominator==0)
{
cout<<"A zero denominator is invalid"<<endl;
exit(1);
}
gcd=(abs(numerator)>abs(denominator)?abs(denominator):abs(numerator));
if(gcd==0) return;
//注意:return语句的特殊用法
if(abs(numerator)>abs(denominator))
{
max=numerator;
min=denominator;
}
else
{
min=numerator;
max=denominator;
}
do
{
gcd=max%min;
max=min;
min=gcd;
}while(gcd!=0);
numerator/=max;
denominator/=max;
if(denominator<0)
{
numerator=-numerator;
denominator=-denominator;
}
}
fraction::fraction(int x,int y)
{
numerator=x;
denominator=y;
}
void fraction::print()
{
cout<<numerator<<"/"<<denominator<<endl;
optim();
}
fraction operator+(fraction &a,fraction &b)
{return( fraction(a.numerator+b.numerator,a.denominator+b.denominator);
}
fraction operator-(fraction &a,fraction &b)
{return( fraction(a.numerator-b.numerator,a.denominator-b.denominator);
}
fraction operator*(fraction &a,fraction &b)
{return( fraction(a.numerator*b.numerator,a.denominator*b.denominator);
}
fraction operator/(fraction &a,fraction &b)
{return (a.numerator*b.denominator,a.denominator*b.numerator);
}
int main()
{
fraction a(2,3),b(3,4),c(0,1),d(0,1),e(0,1),f(0,1);
c=a+b;
d=a-b;
e=a*b;
f=a/b;
cout<<"c="<<endl;c.print();
cout<<"d="<<endl;d.print();
cout<<"e="<<endl;e.print();
cout<<"f="<<endl;f.print();
return 0;
}
额
不知道学过c++没,应该能看懂吧