【C++】分数类运算 加减乘除 约分 运算符重载

要求+、-、=重载为成员函数
*、/ 重载为友元函数
同时还要定义一个最大公约数成员函数去约分

#include <bits/stdc++.h>
using namespace std;
class number
{
	int fz,fm;
public:
	number(int a=0,int b=1)
	{
		fz=a;
		fm=b;
	}
	friend number operator*(number &n1,number &n2);
	friend number operator/(number &n1,number &n2);
	friend int gcd(int a,int b);
	friend int min_gb(int a,number &n1);
	number operator+(number &n1);
	number operator-(number &n1);
	number operator=(const number &n2);
	int show()
	{
		cout<<fz;
		if(fm!=1) cout<<" "<<fm<<endl;
	}
};

int gcd(int a,int b)
{
	if(b==0) return a;
	else return gcd(b,a%b);
}

int min_gb(int a,number &n1)
{
	return a*n1.fm/gcd(a,n1.fm);
} 

number operator/(number &n1,number &n2)
{
	int b;
	number nn;
	nn.fz=n1.fz*n2.fm;
	nn.fm=n1.fm*n2.fz;
	b=gcd(nn.fz,nn.fm);
	if(b!=1)
	{
		nn.fz=nn.fz/b;
		nn.fm=nn.fm/b;
	}
	return nn;	
}

number operator*(number &n1,number &n2)	
{
	int b;
	number nn;
	nn.fz=n1.fz*n2.fz;
	nn.fm=n1.fm*n2.fm;
	b=gcd(nn.fz,nn.fm);
	if(b!=1)
	{
		nn.fz=nn.fz/b;
		nn.fm=nn.fm/b;
	}
	return nn;		
}
number number::operator+(number &n1)
{
	number nn;
	int a=min_gb(fm,n1);
	nn.fm=a;
	nn.fz=(a/fm)*fz+(a/n1.fm)*n1.fz;
	int b=gcd(nn.fz,nn.fm);
	if(b!=1)
	{
		nn.fz=nn.fz/b;
		nn.fm=nn.fm/b;
	}
	return nn;	
}
number number::operator-(number &n1)
{
	number nn;
	int a=min_gb(fm,n1);
	nn.fm=a;
	nn.fz=(a/fm)*fz-(a/n1.fm)*n1.fz;
	int b=gcd(nn.fz,nn.fm);
	if(b!=1)
	{
		nn.fz=nn.fz/b;
		nn.fm=nn.fm/b;
	}
	return nn;
}

number number::operator=(const number &n2)
{
	fz=n2.fz;
	fm=n2.fm;
}

int main()
{
	int a,b,c,d;
	cin>>a>>b>>c>>d;
	number num1(a,b);
	number num2(c,d);
	number num3,num4,num5,num6;
	
	num3=num1+num2;
	cout<<"相加结果为:"<<endl;
	num3.show();
	
	num4=num1-num2;
	cout<<"相减结果为:"<<endl;
	num4.show();
	
	num5=num1*num2;
	cout<<"相乘结果为:"<<endl;
	num5.show();
	
	num6=num1/num2;
	cout<<"相除结果为:"<<endl;
	num6.show();
}
上一篇:2021年N1叉车司机考试APP及N1叉车司机复审考试


下一篇:2021年N1叉车司机考试内容及N1叉车司机考试资料