21xrx.com
2025-03-29 08:10:19 Saturday
文章检索 我的文章 写文章
C++实现复数的加减乘除操作(四则运算)
2023-07-12 15:31:08 深夜i     24     0
C++ 复数 运算 加减乘除 实现

在数学中,复数指具有形如a+bi的形式,其中a和b都是实数,而i是虚数单位。复数的四则运算包括加法、减法、乘法和除法。

C++是一种高级编程语言,可用于计算机科学和软件工程。在C++中,我们可以使用类来定义和操作复数。下面是一个C++类,实现了复数的四则运算:

class Complex {
 private:
  double real, imag;
 public:
  Complex(double r = 0, double i = 0)
    real = r;
    imag = i;
  
  // 加法运算
  Complex operator+(const Complex& c) {
    return Complex(real + c.real, imag + c.imag);
  }
  // 减法运算
  Complex operator-(const Complex& c) {
    return Complex(real - c.real, imag - c.imag);
  }
  // 乘法运算
  Complex operator*(const Complex& c) {
    return Complex(real*c.real - imag*c.imag, real*c.imag + imag*c.real);
  }
  // 除法运算
  Complex operator/(const Complex& c) {
    double denom = c.real*c.real + c.imag*c.imag;
    return Complex((real*c.real + imag*c.imag)/denom, (imag*c.real - real*c.imag)/denom);
  }
};

上述代码中,我们定义了一个名为Complex的类,其中包含私有成员变量real和imag,分别表示复数的实部和虚部。该类还定义了一个名为Complex的构造函数,用于初始化实部和虚部。此外,该类还包括四个运算符重载函数,分别实现复数的加、减、乘和除运算。这些函数都返回一个新的复数对象,该对象包含了运算后的结果。

以下是一个例子,演示了如何使用上述代码进行复数的四则运算:

#include <iostream>
using namespace std;
int main() {
  Complex c1(3, 4);
  Complex c2(2, -1);
  Complex sum = c1 + c2;
  Complex diff = c1 - c2;
  Complex prod = c1 * c2;
  Complex quot = c1 / c2;
  cout << "c1 = " << c1.real << " + " << c1.imag << "i\n";
  cout << "c2 = " << c2.real << " + " << c2.imag << "i\n";
  cout << "Sum = " << sum.real << " + " << sum.imag << "i\n";
  cout << "Difference = " << diff.real << " + " << diff.imag << "i\n";
  cout << "Product = " << prod.real << " + " << prod.imag << "i\n";
  cout << "Quotient = " << quot.real << " + " << quot.imag << "i\n";
  return 0;
}

在上述示例中,我们创建了两个复数c1和c2,并对它们进行加、减、乘和除运算。最后,我们输出了每种运算的结果。输出如下所示:

c1 = 3 + 4i
c2 = 2 + -1i
Sum = 5 + 3i
Difference = 1 + 5i
Product = 10 + 5i
Quotient = 0.4 + 1.6i

由此可见,我们可以使用C++来实现复数的四则运算,非常方便。这对于需要处理复数的科学、工程和数学计算来说是非常有用的。

  
  

评论区

请求出错了