⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ppl1.cpp

📁 分数四则运算的直接实现
💻 CPP
字号:
#include <iostream.h>
#include <math.h>
class complex
{
public:
	complex() {real=imag=0;}
		complex(int r,int i)
	{
		real=r;imag=i;
	}
	complex operator +(const complex &c);
	complex operator -(const complex &c);
	complex operator *(const complex &c);
	complex operator /(const complex &c);
	//complex operator <(const complex r);
	//complex operator >(const complex &c);
    //complex operator =(const complex &c);
	friend void print(const complex &c);
    //friend void print1(const complex &c);
    
private:
	int real,imag;//real分子imag分母 
};

	inline complex complex::operator +(const complex &c)
	{
		
		if(c.imag==imag)
			return complex((real+c.real),imag);
		else
		    return complex((real*c.imag+c.real*imag),(imag*c.imag));
	}

	inline complex complex::operator -(const complex &c)
	{
		if(c.imag==imag)
            return complex((real-c.real),imag);
		else
		    return complex((real*c.imag-c.real*imag),(imag*c.imag));
	}

    inline complex complex::operator *(const complex &c)
	{
		return complex(real*c.real,imag*c.imag);
	}

    inline complex complex::operator /(const complex &c)
	{
		return complex((real*c.imag),(c.real*imag));
	}


void print(const complex &c)
{
	int s,x,y;// s 是余数
	x=c.real;
	y=c.imag;

	if(c.real==0)//出现分母为0,而分子不为0时
	{  cout<<"0";
	   goto end;
	}

    if(c.imag==0)//出现分子为0,而分母不为0时
	{  cout<<"\n分母不能为0";
	   goto end;
	}

    if(c.imag==c.real)//出现分子分母相同时
	{	cout<<"1";
	    goto end;
	}

	if(c.imag==-(c.real))//出现分子分母的绝对值相同时
	{	cout<<"-1";
		goto end;
	}

	s=y%x;
	while(s!=0)//(s=y%x)!=0    化简部分
	{ y=x;x=s;s=y%x;} 

	 if(c.real/x<0||c.imag/x<0)   //    输出部分
	 {	if(c.imag/x==1)
			   cout<<"-"<<abs(c.real/x);
		    else
	           cout<<"-"<<abs(c.real/x)<<"/"<<abs(c.imag/x)<<endl;
	 }
	 else
	 {  if(c.imag/x==1)
			  cout<<c.real;
		else
			  cout<<c.real/x<<"/"<<c.imag/x<<endl;
	 }
end:;
}




	void main()
	{
		int a,b,c,d;
        cout<<"分别输入两对分子和分母:";
       k:cin>>a>>b>>c>>d;
		if(b==0||d==0)
		{
			cout<<"分母不能为0,请重新输入:";
			goto k;
		}
        
		complex c1(a,b),c2(c,d),c3;
		c3=c1+c2;
		cout<<"\nc1+c2=";
		print(c3);
        c3=c1-c2;
		cout<<"\nc1-c2=";
		print(c3); 
		
		c3=c1*c2;
		cout<<"\nc1*c2=";
		print(c3);
		c3=c1/c2;
		cout<<"\nc1/c2=";
		print(c3);
		
		cout<<endl;
	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -