21xrx.com
2025-03-27 16:32:04 Thursday
文章检索 我的文章 写文章
C++编写一个简单的复数计算器
2023-07-05 02:03:15 深夜i     21     0
C++ 复数计算器 简单

在数学中,复数是一种有着实部和虚部的数。在编程中,复数的计算也是一个常见的问题。本篇文章将介绍如何使用C++编写一个简单的复数计算器。

首先我们需要定义一个复数类,该类包含两个数据成员:实部和虚部,以及一些基本的操作函数。例如,我们可以定义一个构造函数和一个析构函数来初始化和销毁对象。同时,我们还可以重载一些运算符,比如加号、减号、乘号和除号来实现复数的加减乘除计算。

接下来让我们来看一下代码:

#include<iostream>
using namespace std;
class Complex
{
  private:
    double real;  //实部
    double imag;  //虚部
  public:
    Complex(double r = 0, double i = 0): real(r), imag(i) {}  //构造函数
    ~Complex() {}  //析构函数
    Complex operator+(const Complex& other) const  //重载加号
    {
      Complex res;
      res.real = this->real + other.real;
      res.imag = this->imag + other.imag;
      return res;
    }
    Complex operator-(const Complex& other) const  //重载减号
    
      Complex res;
      res.real = this->real - other.real;
      res.imag = this->imag - other.imag;
      return res;
    
    Complex operator*(const Complex& other) const  //重载乘号
    {
      Complex res;
      res.real = this->real * other.real - this->imag * other.imag;
      res.imag = this->real * other.imag + this->imag * other.real;
      return res;
    }
    Complex operator/(const Complex& other) const  //重载除号
    {
      Complex res;
      double d = other.real * other.real + other.imag * other.imag;
      res.real = (this->real * other.real + this->imag * other.imag) / d;
      res.imag = (this->imag * other.real - this->real * other.imag) / d;
      return res;
    }
    void show() const  //输出复数
    {
      cout << "(" << real << " + " << imag << "i)" << endl;
    }
};
int main()
{
  Complex c1(1, 2);
  Complex c2(3, 4);
  Complex c3 = c1 + c2;
  c3.show();
  Complex c4 = c1 - c2;
  c4.show();
  Complex c5 = c1 * c2;
  c5.show();
  Complex c6 = c1 / c2;
  c6.show();
  return 0;
}

在上面的代码中,我们定义了一个名为Complex的类,其中包含了一个构造函数和一个析构函数,以及四个重载运算符函数。我们使用了一个复数对象c1和c2进行加减乘除计算,并输出了结果。

在测试时,通过构造函数初始化了两个复数c1和c2,分别代表1+2i和3+4i。我们利用上面定义的运算符函数分别对它们进行加减乘除,得到了四个中间结果。最后我们将这些结果输出,得到了最终的答案。

总体来说,这是C++编写一个简单的复数计算器的代码示例。当然,这只是一个很简单的例子,实际上复数可以进行更加复杂的计算。在实际应用中,需要根据具体的需求来对复数类进行相应的设计和实现。

  
  

评论区