分数类的重载
要求输入输出·:5
1 2 4 5 7 8 9 6 2 5
8
5 8 7 3 6 7 4 9 3 8 2 7 8 3 6 5
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
class Fraction
{
private:
int z,m;
public:
Fraction(int zz=0,int mm=0)
{
z=zz;
m=mm;
}
Fraction(Fraction &p)
{
z=p.z;
m=p.m;
}
bool Check ();//调用化简分数的函数。
operator double()const
{
return z/m;//类型转换。
}
Fraction operator+(Fraction &p)//四则运算
{
int a,b;
b=m*p.m;
a=z*p.m+p.z*m;
return Fraction(a,b);
}
Fraction operator-(Fraction &p)
{
int a,b;
b=m*p.m;
a=z*p.m-p.z*m;
return Fraction(a,b);
}
Fraction operator*(Fraction &p)
{
int a,b;
b=m*p.m;
a=z*p.z;
return Fraction(a,b);
}
Fraction operator/(Fraction &p)
{
int a,b;
b=m*p.z;
a=z*p.m;
return Fraction(a,b);
}
friend ostream&operator<<(ostream &o,Fraction &p)//输出重载
{
if(p.Check()==0)
o<<"cuowu";
else
{
o<<p.z<<"/"<<p.m;
}
return o;
}
friend istream&operator>>(istream &i,Fraction &p)//输入重载
{
i>>p.z>>p.m;
return i;
}
};
bool Fraction::Check()//判断分母是否为零,并且化简,
{
if(m==0)
return false;
else
{
int x=z,y=m;
int t=y;
while(x%y!=0)
{
t=x%y;
x=y;
y=t;
}
z=z/t;
m=m/t;
if(m<0)
{
m=-(m);
z=-(z);
}
return true;
}
}
int main()
{
cout<<fixed<<showpoint<<setprecision(3); //前面要加语句#include<iomanip>
Fraction f1(0,1),f2(-1,-2),f3(2,-4);
cout<<"f1="<<f1<<"f2="<<f2<<"f3="<<f3<<endl;
int i,j,n;
Fraction t;
while(cin>>n)
{
Fraction *p=new Fraction;
for(i=0;i<n;i++)
cin>>p;
for(i=0;i<n-1;i++)
for(j=0;j<n-i-1;j++)
if((double)p>(double)p)
{
t=p;
p=p;//调用复制运算的函数
p=t;
}
cout<<p;
for(i=1;i<n;i++)
cout<<","<<p;
cout<<endl;
}
return 0;
}
你是在提问题吗?
你的问题是? 就我代码输出不了题目所需的,您看,虽然是挺难查的,谢谢您,好人一生平安
页:
[1]