马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<iostream.h>
#include<math.h>
class Rational
{
public:
Rational(int u=0,int d=1)
{
up=u;
down=d;
}
Rational(double a);
operator double();
void setval();
void showNnomal();
friend Rational operator+(Rational &r1);
friend Rational operator*(Rational &r1);
friend ostream& operator<<(ostream&,Rational&);
private:
int up;
int down;
int Maxdivisor(int x,int y)
{
int z=x%y;
while(z)
{x=y;
y=z;
z=x%y;
}
return y;
}
int Minmultiple(int x,int y)
{
int p=Maxdivisor(x,y);
int z=x*y/p;
return z;
}
};
Rational Rational::Rational(double a)
{
int a1=(int)a,count=0;
double a2=a-a1;
while(a2!=0)
{
count=count+1;
a=10*a2;
a1=(int)a;
a2=a-a1;
}
double b=pow(10,count);
a=a*b;
int c=(int)a;
int g=Maxdivisor(c,(int)b);
up=c/g;
down=(int)b/g;
}
Rational::operator double()
{
double x;
int u=(double)up;
int d=(double)down;
x=u/d;
return x;
}
void Rational::setval()
{
cin>>up;
cin>>down;
}
void Rational::showNnomal()
{
int g,u,d;
g=Maxdivisor(up,down);
u=up/g;
d=down/g;
cout<<u<<"/"<<d<<endl;
}
Rational Rational::operator+(Rational &r1)
{
int i=this->down*r1.down;
int r=this-> up*r1.down+down*r1.up;
int d=Maxdivisor(r,i);
return Rational(r/d,i/d);
}
Rational Rational::operator*(Rational &r1)
{
int i=this->down*r1.down;
int r=this-> up*r1.up;
int d=Maxdivisor(r,i);
return Rational(r/d,i/d);
}
ostream& operator<<(ostream& output,Rational&c);
{
output<<c.up<<"/"<<c.down<<endl;
}
int main()
{
Rational r1(4,14),r2(5,8),r3,r4;
cout<<"the r1 is:";
r1.showNomal();
cout<<"the r2 is:";
r2.showNomal();
r3=r1*r2;
cout<<"the r1*r2 is:"<<r3<<endl;
r4=r1+r2;
cout<<"the r1+r2 is:"<<r4<<endl;
r1.setval();
r2.setval();
r4=r1+r2;
cout<<"the r1+r2 is:"<<r4<<endl;
double a;
cout<<"输入一个实数";
cin>>a;
r4=r1+Rational(a);
cout<<"the r1 is:"<<r1<<endl;
cout<<"the r1+"<<a<<"is:"<<r4;
a=r4;
cout<<"="<<a<<endl;
return 0;
}
Rational Rational::Rational(double a);
不能在构造函数上返回类型!!!!
|