C++定义描述复数的结构体类型变量,实现复数的输入输出。设计三个函数实现复数的加法,减法和乘法运算

2024-11-08 04:40:25
有1个网友回答
网友(1):

给你个类的吧,c++中一般不用结构体
#include
//using namespace std;

class complex
{
private:
float real;
float image;
public:
complex(float r=0,float i=0)
{
real=r;
image=i;
}
/*
void display()
{
cout< }
*/
complex operator +(complex &obj)
{
complex c;
c.real=real+obj.real;
c.image=image+obj.image;
return c;
}

complex operator -(complex &obj)
{
complex c;
c.real=real-+obj.real;
c.image=image-obj.image;
return c;
}

complex operator *(complex &obj)
{
complex c;
c.real=real*obj.real-image*obj.image;
c.image=image*obj.real+obj.image*real;
return c;
}

complex operator /(complex &obj)
{
complex c;
c.real=real*obj.real+image*obj.image;
c.image=image*obj.real-obj.image*real;
float A=obj.real*obj.real+obj.image*obj.image;
c.real=c.real/A;
c.image=c.image/A;
return c;
}

friend ostream & operator<<(ostream & ,complex &);

};

ostream & operator<<(ostream &out ,complex &obj)
{
out< return out;
}

//3 ^ 2 ===>9

int main()
{
complex c1(3,4);
complex c2(c1);
//complex c3(-12,30);
cout< cout< complex c;

c=c1+c2;
cout< c=c1-c2;
cout< c=c1*c2;
cout< c=c1/c2;
cout< return 0;
}