21xrx.com
2024-09-20 05:52:48 Friday
登录
文章检索 我的文章 写文章
C++中如何定义虚数?
2023-07-01 16:31:13 深夜i     --     --
C++ 定义 虚数

在C++中,可以通过定义一个带有虚数部分的复数类来表示虚数。

复数是由实部和虚部组成的数字,可以表示为 a + bi 的形式。其中 a 是实部,b 是虚部,i 是一个虚数单位,定义为 i² = -1。

在C++中,可以定义一个复数类,将实部和虚部作为成员变量,并在类中重载运算符来进行加、减、乘、除等操作。

以下是一个示例代码:


class Complex {

private:

  double real;

  double imaginary;

public:

  Complex(double r, double i)

    real = r;

    imaginary = i;

  

  // 重载加法运算符

  Complex operator+(const Complex& other) {

    double r = real + other.real;

    double i = imaginary + other.imaginary;

    return Complex(r, i);

  }

  // 重载减法运算符

  Complex operator-(const Complex& other) {

    double r = real - other.real;

    double i = imaginary - other.imaginary;

    return Complex(r, i);

  }

  // 重载乘法运算符

  Complex operator*(const Complex& other) {

    double r = real * other.real - imaginary * other.imaginary;

    double i = real * other.imaginary + imaginary * other.real;

    return Complex(r, i);

  }

  // 重载除法运算符

  Complex operator/(const Complex& other) {

    double r = (real * other.real + imaginary * other.imaginary) / (other.real * other.real + other.imaginary * other.imaginary);

    double i = (imaginary * other.real - real * other.imaginary) / (other.real * other.real + other.imaginary * other.imaginary);

    return Complex(r, i);

  }

  // 获取实部

  double getReal() const

    return real;

  

  // 获取虚部

  double getImaginary() const

    return imaginary;

  

};

int main() {

  // 定义两个复数

  Complex c1(2, 3);

  Complex c2(4, -2);

  // 计算两个复数的和、差、积、商,并输出结果

  Complex sum = c1 + c2;

  Complex diff = c1 - c2;

  Complex product = c1 * c2;

  Complex quotient = c1 / c2;

  cout << "和:" << sum.getReal() << " + " << sum.getImaginary() << "i" << endl;

  cout << "差:" << diff.getReal() << " + " << diff.getImaginary() << "i" << endl;

  cout << "积:" << product.getReal() << " + " << product.getImaginary() << "i" << endl;

  cout << "商:" << quotient.getReal() << " + " << quotient.getImaginary() << "i" << endl;

  return 0;

}

在上面的代码中,我们定义了一个复数类 Complex,将实部和虚部作为成员变量,并重载了加、减、乘、除等运算符,可以方便地进行复数的计算。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复