|
楼主 |
发表于 2016-3-27 15:37:51
|
显示全部楼层
[code]#include<iostream>
class Younumber
{
public:
Younumber();
Younumber(int a);
Younumber(int a,int b);
friend Younumber operator+(Younumber &p,Younumber &q);//把它改为传引用了,但是这样后,下面的p+q+d运算就提示错误了,但是我只p+q的话是可以的,就是不能多次运算,这是为什么嘞
friend std::ostream& operator<<(std::ostream &cout,Younumber &p);//以分数形式打印出来
protected:
int fenzi;//分子
int fenmu;//分母
};
Younumber::Younumber()
{
fenzi=0;
fenmu=0;
}
Younumber::Younumber(int a,int b)
{
fenzi=a;
fenmu=b;
}
Younumber ::Younumber(int a)
{
fenzi=a;
fenmu=a;
}
std::ostream& operator<<(std::ostream &cout,Younumber &p)
{
if(p.fenzi%p.fenmu==0)
{
std::cout<<p.fenzi;
}
else
{
std::cout<<p.fenzi<<"/"<<p.fenmu;
}
}
Younumber operator+(Younumber &p,Younumber &q)
{ Younumber e;
//下面就是进行运算,还有进行分子分母约分的处理
if(p.fenmu!=q.fenmu)
{
e.fenzi=p.fenzi*q.fenmu+q.fenzi*p.fenmu;
e.fenmu=p.fenmu*q.fenmu;
if(e.fenmu>=e.fenzi)
{ int num=e.fenzi;
while(e.fenzi%num!=0||e.fenmu%num!=0)
{
num--;
}
e.fenzi=e.fenzi/num;
e.fenmu=e.fenmu/num;
}
else
{
int num=e.fenmu;
while(e.fenzi%num!=0||e.fenmu%num!=0)
{
num--;
}
e.fenzi=e.fenzi/num;
e.fenmu=e.fenmu/num;
}
}
else
{
e.fenzi=p.fenzi+q.fenzi;
e.fenzi=p.fenzi;
}
return e;
}
int main()
{
Younumber p(10,100);
Younumber q(100,10);
Younumber d(3,100);
Younumber c;
c=p+q+d;
std::cout<<c;
return 0;
} |
|