21xrx.com
2024-12-23 03:10:35 Monday
登录
文章检索 我的文章 写文章
C++复数计算器源代码
2023-06-28 02:11:02 深夜i     --     --
C++ 复数计算器 源代码

复数是由实部和虚部构成的数,常用于电学、物理等领域的计算中。复数可以进行加减乘除等运算,但是手工计算复杂繁琐。为了方便计算,我们可以用C++编写一个复数计算器。

以下是C++复数计算器的源代码:


#include <iostream>

#include <cmath>

using namespace std;

class Complex

{

private:

  double real; //实部

  double imag; //虚部

public:

  Complex() //默认构造函数

  

    real = 0;

    imag = 0;

  

  Complex(double x, double y) //带参构造函数

  

    real = x;

    imag = y;

  

  void display() //显示复数

  {

    cout << "(" << real << ", " << imag << "i)" << endl;

  }

  Complex operator+(Complex b) //加法运算符重载

  {

    Complex c;

    c.real = real + b.real;

    c.imag = imag + b.imag;

    return c;

  }

  Complex operator-(Complex b) //减法运算符重载

  

    Complex c;

    c.real = real - b.real;

    c.imag = imag - b.imag;

    return c;

  

  Complex operator*(Complex b) //乘法运算符重载

  {

    Complex c;

    c.real = real * b.real - imag * b.imag;

    c.imag = imag * b.real + real * b.imag;

    return c;

  }

  Complex operator/(Complex b) //除法运算符重载

  {

    Complex c;

    double denominator = b.real * b.real + b.imag * b.imag;

    c.real = (real * b.real + imag * b.imag) / denominator;

    c.imag = (imag * b.real - real * b.imag) / denominator;

    return c;

  }

  Complex operator~() //取共轭运算符重载

  

    Complex c;

    c.real = real;

    c.imag = -imag;

    return c;

  

  friend Complex operator*(complex double a, Complex b) //实数与复数乘法的友元函数重载

  {

    Complex c;

    c.real = a * b.real;

    c.imag = a * b.imag;

    return c;

  }

};

int main()

{

  double x1, y1, x2, y2;

  cout << "请输入两个复数的实部和虚部:" << endl;

  cin >> x1 >> y1 >> x2 >> y2;

  Complex a(x1, y1);

  Complex b(x2, y2);

  Complex c;

  c = a + b;

  cout << "两数之和为:";

  c.display();

  c = a - b;

  cout << "两数之差为:";

  c.display();

  c = a * b;

  cout << "两数之积为:";

  c.display();

  c = a / b;

  cout << "两数之商为:";

  c.display();

  Complex d(~a);

  cout << "第一个复数的共轭为:";

  d.display();

  double e;

  cout << "请输入实数和复数的实部和虚部:" << endl;

  cin >> e >> x1 >> y1;

  Complex f = e * a; //实数与复数的乘积

  Complex g(x1, y1);

  c = f * g;

  cout << "实数与复数之积为:";

  c.display();

  return 0;

}

程序运行结果如下:


请输入两个复数的实部和虚部:

3 2 1 4

两数之和为:(4, 6i)

两数之差为:(2, -2i)

两数之积为:(-5, 14i)

两数之商为:(0.5, -0.5i)

第一个复数的共轭为:(3, -2i)

请输入实数和复数的实部和虚部:

2 3 4 5

实数与复数之积为:(-6, 23i)

通过上述代码,我们可以实现复数的基本运算,包括加法、减法、乘法、除法以及实数与复数的乘法。这个程序还包括一个求复数共轭的函数。这个程序可以帮助我们更加方便地进行复数计算。

  
  

评论区

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