分数加法运算重载
一、
1.分数为0时,表示成0z1m,如果结果为负数,那么分子取负数,分母为正数
二、
三、
#include <iostream>
using namespace std;
class FS
{
private:
int fz;
int fm;
public:
FS(){}
FS(int z,int m):fz(z),fm(m){}
void set(int x,int y) {fz=x; fm=y;}
int measure(int x,int y);
void show() const
{
cout <<fz<<"z"<<fm<<"m"<<endl;
}
FS operator + (const FS &f)
{
int y=fm*f.fm;
int x=fz*f.fm+f.fz*fm;
int a=measure(x,y);
x=x/a;
y=y/a;
if(y<0)
{
x=-x;
y=-y;
}
return FS(x,y);
}
};
int FS::measure(int x,int y)
{
int z = y;
while(x%y!=0)
{
z = x%y;
x = y;
y = z;
}
return z;
}
int main()
{
int n;
cin>>n;
int i;
int fz,fm;
//int x[50],y[50];
char a,b;
FS *f = new FS[n*2];
FS *f1 = new FS[n];
for(i=0;i<n*2;i++)
{
cin>>fz>>a>>fm>>b;
f[i].set(fz,fm);
}
int j=0;
for(i=0;i<n*2;i++)
{
f1[j]=f[i]+f[i+1];
i++;
j++;
}
for(i=0;i<n;i++)
{
f1[i].show();
}
return 0;
}
四、
#include <iostream>
using namespace std;
class FS
{
private:
int fz;
int fm;
public:
FS(){}
FS(int z,int m):fz(z),fm(m){}
void set(int x,int y) {fz=x; fm=y;}
int measure(int x,int y);
void show() const
{
cout <<fz<<"z"<<fm<<"m"<<endl;
}
FS operator + (const FS &f)
{
int y=fm*f.fm;
int x=fz*f.fm+f.fz*fm;
int a=measure(x,y);
x=x/a;
y=y/a;
if(y<0)
{
x=-x;
y=-y;
}
return FS(x,y);
}
};
int FS::measure(int x,int y)
{
int z = y;
while(x%y!=0)
{
z = x%y;
x = y;
y = z;
}
return z;
}
int main()
{
int n;
cin>>n;
int i;
int fz,fm;
//int x[50],y[50];
char a,b;
FS *f = new FS[n*2];
FS *f1 = new FS[n];
for(i=0;i<n*2;i++)
{
cin>>fz>>a>>fm>>b;
f[i].set(fz,fm);
}
int j=0;
for(i=0;i<n*2;i++)
{
f1[j]=f[i]+f[i+1];
i++;
j++;
}
for(i=0;i<n;i++)
{
f1[i].show();
}
return 0;
}