21xrx.com
2025-03-26 13:06:43 Wednesday
文章检索 我的文章 写文章
C++实现复数运算
2023-07-05 08:10:05 深夜i     12     0
C++ 复数 运算

复数是一个数学概念,它由实部和虚部组成,以"a+bi"的形式表示。其中,a为实部,b为虚部,i为虚数单位。在C++中,我们可以用复数类来实现复数运算。

首先,我们需要定义一个复数类,包括实部和虚部两个成员变量。然后我们可以定义一些构造函数、析构函数和运算符重载函数。例如,我们可以通过重载加、减、乘、除等运算符来实现复数的运算。下面是一个示例代码:

class Complex {
public:
  Complex(double real = 0.0, double imag = 0.0); // 构造函数
  Complex(const Complex& other); // 拷贝构造函数
  ~Complex(); // 析构函数
  Complex operator+(const Complex& other); // 加法运算
  Complex operator-(const Complex& other); // 减法运算
  Complex operator*(const Complex& other); // 乘法运算
  Complex operator/(const Complex& other); // 除法运算
  Complex& operator=(const Complex& other); // 赋值运算符
private:
  double _real; // 实部
  double _imag; // 虚部
};
Complex::Complex(double real, double imag) : _real(real), _imag(imag) {}
Complex::Complex(const Complex& other)
  _real = other._real;
  _imag = other._imag;
Complex::~Complex() {}
Complex Complex::operator+(const Complex& other) {
  return Complex(_real + other._real, _imag + other._imag);
}
Complex Complex::operator-(const Complex& other) {
  return Complex(_real - other._real, _imag - other._imag);
}
Complex Complex::operator*(const Complex& other) {
  return Complex(_real*other._real - _imag*other._imag, _real*other._imag + _imag*other._real);
}
Complex Complex::operator/(const Complex& other) {
  double denom = other._real*other._real + other._imag*other._imag;
  return Complex((_real*other._real + _imag*other._imag) / denom, (_imag*other._real - _real*other._imag) / denom);
}
Complex& Complex::operator=(const Complex& other) {
  _real = other._real;
  _imag = other._imag;
  return *this;
}

上面的代码实现了复数类的定义,并重载了加、减、乘、除和赋值运算符。其中,加、减、乘、除的计算方式是通过实部和虚部之间的运算实现的。

接下来,我们可以使用定义好的复数类来进行运算。例如:

Complex a(4, 3);
Complex b(2, -5);
Complex c = a + b;
Complex d = a - b;
Complex e = a * b;
Complex f = a / b;

上面的代码创建了两个复数a和b,分别为(4+3i)和(2-5i),然后用加、减、乘、除运算符对它们进行操作。结果分别为:

a + b = (6-2i)
a - b = (2+8i)
a * b = (23-14i)
a / b = (0.08+0.64i)

总的来说,C++实现复数运算需要定义一个复数类,并重载加、减、乘、除等运算符来实现复数运算。这样就可以方便地对复数进行运算。

  
  

评论区