c++ 复数运算

//定义复数类complex class complex{ private: int real; //实部 int image; //虚部 public: complex(int x=0,int y=0){ real = x; image = y; } //构造函数 //重载加号运算符,功能为:两个复数对象相加 friend complex operator + (const complex& a, const complex& b) { complex c; c.real = a.real + b.real; c.image = a.image + b.image; return c; } } //使用 complex a(2,5),b(7,8),c; c = a + b;

 

#include<iostream.h>
#include<math.h>


class Complex
{
public:
 Complex()
 {
  this->real=0;
  this->image=0;
 }
 Complex(double a,double b);
 Complex(const Complex &c);
 void showComplex() const
 {
  if(image<0)
  {
   cout<<"("<<real<<image<<"i"<<")";
  }else{
   cout<<"("<<real<<"+"<<image<<"i"<<")";
  }
 }
 void setComplex(double a,double b)
 {
  real=a;
  image=b;
 }
 double getReal() const
 {
  return real;
 }
 double getImage() const
 {
  return image;
 }
 Complex getConj() const
 {
  Complext c(real,-image);
  return c;
 }
 double getAbs() const
 {
  return sqrt(real*real+image*image);
 }
 double getInstance(const Complex &c)
 {
  return sqrt((real-c.real)*(real-c.real)+(image-c.image)*(image-c.image));
 }
 Complex operator +(const Complex &a)
 {
  return Complex(real+a.real,image+a.image);
 }
 Complex operator +(const double a) const
 {
  return Complex(real+a,image);
 }
 Complex operator -(const Complex &b)
 {
  return Complex(real-b.real,image-b.image);
 }
 Complex operator -(const double b)
 {
  return Complex(real-b,image);
 }
 Complex operator *(const Complex &c)
 {
  return Complex(real*c.real,image*c.image);
 }
 Complex operator *(const double c)
 {
  return Complex(real*c,image);
 }
 Complex operator /(const Complex &c)
 {
  return Complex((real*c.real+image*c.image)/(c.real*c.real+c.image*c.image),(image*c.real-real*c.image)/(c.real*c.real+c.image*c.image));
 }
 Complex operator /(const double c)
 {
  return Complex(real/c,image/c);
 }
 Complex operator =(const Complex &c)
 {
  return Complex(c.real,c.image);
 }
 bool operator==(const Complex &c) const;
private:
 double real;
 double image;
};
Complex::Complex(double a,double b)
{
 this->real=a;
 this->image=b;
}

Complex::Complex(const Complex &c)
{
 real=c.real;image=c.image;
}
bool Complex::operator==(const Complex &c)
{
 if(c.real==real && c.image==image)
  return true;
 else
  return false;
}
void main(void)
{
 cout<<"OK"<<endl;
 Complex z1(23.12,234.1);
 Complex z2(21.2,-89.09);
 z1.showComplex();
 cout<<"/";
 z2.showComplex();

 Complex z3;
 z3=z1/z2;
 cout<<"=";
 z3.showComplex();
 cout<<endl;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值