-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplex_numbers.cpp
More file actions
63 lines (50 loc) · 1.85 KB
/
complex_numbers.cpp
File metadata and controls
63 lines (50 loc) · 1.85 KB
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
#include "complex_numbers.h"
#include <cmath>
#include <iostream>
complex_numbers::complex_numbers(double r, double i) : real(r), imaginary(i) {}
double complex_numbers::get_real() const {
return real;
}
double complex_numbers::get_imaginary() const {
return imaginary;
}
double complex_numbers::abs(){
return std::sqrt(real * real + imaginary * imaginary);
}
complex_numbers& complex_numbers::operator+=(const complex_numbers& other){
real += other.real;
imaginary += other.imaginary;
return *this;
}
complex_numbers& complex_numbers::operator-=(const complex_numbers& other){
real -= other.real;
imaginary -= other.imaginary;
return *this;
}
complex_numbers& complex_numbers::operator*=(const complex_numbers& other){
double new_real = real * other.real - imaginary * other.imaginary;
double new_imaginary = real * other.imaginary + other.real * imaginary;
real = new_real;
imaginary = new_imaginary;
return *this;
}
std::ostream& operator<<(std::ostream& out, const complex_numbers& complex){
if(complex.imaginary >= 0){
out << complex.real << "+" << complex.imaginary << "i";
} else {
out << complex.real << complex.imaginary << "i";
}
return out;
}
complex_numbers const operator+(const complex_numbers& l, const complex_numbers& r){
return complex_numbers(l.get_real() + r.get_real(), l.get_imaginary() + r.get_imaginary());
}
complex_numbers const operator-(const complex_numbers& l, const complex_numbers& r){
return complex_numbers(l.get_real() - r.get_real(), l.get_imaginary() - r.get_imaginary());
}
complex_numbers const operator*(const complex_numbers& l, const complex_numbers& r){
return complex_numbers(
l.get_real() * r.get_real() - l.get_imaginary() * r.get_imaginary(),
l.get_real() * r.get_imaginary() + r.get_real() * l.get_imaginary()
);
}