Level 2 : Project 6
1) We want to create a class called Complex to handle complex numbers:
Attributes:
re the real part of type double
img the imaginary part of type double
Methods:
Constructor with arguments (default initialization values)
Display function
Function that returns the module knowing that: |z| = √(a²+b²)
Function which returns the conjugate knowing that: z = a - bi
Overload of the following operators:
+ : for (complex + complex) knowing that: ( a + bi ) + ( c + di ) = ( a + c ) + ( b + d )i
The same for - and * knowing that : ( a + bi ) * ( c + di ) = ( ac - bd ) + ( ad + bc)i
2) Create a main() test program.
Solution :
import 'dart:math';
class Complex {
double re, img;
Complex([this.re = 0, this.img = 0]);
void display() {
if (img >= 0)
print("z = $re + $img i");
else
print("z = $re - ${-img} i"); // to avoid a+-bi
}
double module() => sqrt(re * re + img * img);
Complex conjugate() => Complex(re, -img);
Complex operator +(Complex c) => Complex(re + c.re, img + c.img);
Complex operator -(Complex c) => Complex(re - c.re, img - c.img);
Complex operator *(Complex c) =>
Complex(re * c.re - img * c.img, re * c.img + img + c.re);
}
void main() {
var c1 = Complex(), c2 = Complex(2, 7), c3 = Complex(3, -5);
c1.display();
c2.display();
c3.display();
print(c2.module());
c3.conjugate().display();
(c2 + c3).display();
(c2 - c3).display();
(c2 * c3).display();
}
z = 2.0 + 7.0 i
z = 3.0 - 5.0 i
7.280109889280518
z = 3.0 + 5.0 i
z = 5.0 + 2.0 i
z = -1.0 + 12.0 i
z = 41.0 + 0.0 i