使用VC6.0编写运算符+、-、*、/,实现复数间的四则运算
时间: 2024-01-27 16:06:17 浏览: 87
运用C语言编写复数的四则运算.docx
以下是实现复数间四则运算的示例代码:
```cpp
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {};
Complex operator+(const Complex& c2);
Complex operator-(const Complex& c2);
Complex operator*(const Complex& c2);
Complex operator/(const Complex& c2);
void display();
private:
double real;
double imag;
};
Complex Complex::operator+(const Complex& c2)
{
return Complex(real + c2.real, imag + c2.imag);
}
Complex Complex::operator-(const Complex& c2)
{
return Complex(real - c2.real, imag - c2.imag);
}
Complex Complex::operator*(const Complex& c2)
{
return Complex(real*c2.real - imag*c2.imag, real*c2.imag + imag*c2.real);
}
Complex Complex::operator/(const Complex& c2)
{
double r = c2.real*c2.real + c2.imag*c2.imag;
return Complex((real*c2.real + imag*c2.imag) / r, (imag*c2.real - real*c2.imag) / r);
}
void Complex::display()
{
cout << "(" << real << "," << imag << "i)" << endl;
}
int main()
{
Complex a(1, 2), b(3, 4);
Complex c = a + b;
c.display();
c = a - b;
c.display();
c = a * b;
c.display();
c = a / b;
c.display();
return 0;
}
```
在上述示例代码中,我们定义了一个复数类`Complex`,并重载了运算符`+`、`-`、`*`、`/`。在`main`函数中,我们定义了两个复数`a`和`b`,并使用重载的运算符进行四则运算,并将结果赋给变量`c`,最后输出结果。
阅读全文