-
Notifications
You must be signed in to change notification settings - Fork 0
/
complex.cpp
98 lines (86 loc) · 2.03 KB
/
complex.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "complex.hpp"
Complex::Complex(double real, double imag) :
real(real), imag(imag)
{
}
//get real part
double Complex::get_real() const {
return real;
}
//get imag part
double Complex::get_imag() const {
return imag;
}
//set real and imag
void Complex::set_num(double re, double im){
real = re;
imag = im;
}
void Complex::set_real(double re){
real = re;
}
void Complex::set_imag(double im){
imag = im;
}
Complex& Complex::add(const Complex &num){
real += num.real;
imag += num.imag;
return *this;
}
Complex& Complex::sub(const Complex &num){
real -= num.real;
imag -= num.imag;
return *this;
}
Complex& Complex::mul(const Complex &num){
double a = this->real;
double b = this->imag;
double c = num.real;
double d = num.imag;
real = a*c - b*d;
imag = a*d + c*b;
return *this;
}
double Complex::abs() const{
return sqrt(real*real + imag*imag);
}
std::ostream& operator << (std::ostream &out, const Complex &num){
char sign = (num.imag >= 0)? '+': '-';
double im = (num.imag >= 0)? num.imag : -num.imag;
out << num.real << sign << im << 'i';
return out;
}
std::istream& operator >> (std::istream &inp, Complex &num){
inp >> num.real >> num.imag;
return inp;
}
bool Complex::operator == (const Complex &b) const{
return (real == b.real)&&(imag == b.imag);
}
bool Complex::operator != (const Complex &b) const{
return !(*this == b);
}
Complex Complex::operator +(const Complex &num) const{
Complex copy = *this;
return copy.add(num);
}
Complex Complex::operator -(const Complex &num) const{
Complex copy = *this;
return copy.sub(num);
}
Complex Complex::operator *(const Complex &num) const{
Complex copy = *this;
return copy.mul(num);
}
Complex Complex::operator +=(const Complex &num){
this->add(num);
return *this;
}
Complex Complex::operator -=(const Complex &num){
this->sub(num);
return *this;
}
Complex Complex::operator *=(const Complex &num){
this->mul(num);
return *this;
}