A complex number is a number of the form
a + b * i
where, for our purposes, a and b are numbers of type double, and i is a number that represents the quantity square root of -1.
We represent a complex number as two values of type double. Name the member variables real and imaginary. (The variable for the number that is multiplied by i is the one called imaginary). Call the class ComplexNo.
Include a constructor with two parameters of type double that can be used to set the member variables of an object of any values. Also include a default parameter that initializes an object to 0 (that is 0 + 0 * i).
Overload all of the following operators so that they can correctly apply to the numbers of type ComplexNo:
Arithmetic operators
Assignment operators
Other operators
Other operators (Suggestions: the followings can be defined as the friend functions in the class).
Useful information:
(a) Two complex numbers are equal if and only their corresponding real and imaginary parts are equal.
(b) To add or to subtract two complex numbers, you add or subtract the corresponding two (real or imaginary) member variables of type double.
(c) The product of two complex numbers is given by the following formula:
(a + b*i) * (c + d *i) = (a * c b * d) + (a * d + b * c) * i
(d) The division of two complex numbers is given by the following formula: (Hope my derivation was correct :)
Let s = c * c + d * d,
(a + b*i) / (c + d*i) = (a * c + b * d) / s + (b * c – a * d) / s * i
provided s != 0
Proposed class complexNo to start with
class ComplexNo {
// A few friend functions. For example
friend ostream& operator<< (ostream&, ComplexNo&);
public:
// Two constructore
ComplexNo ();
ComplexNo ( double, double);
// Proposed arithmetic and assignment arithmetic operators,
// for example
ComplexNo operator+ (const ComplexNo&) const;
ComplexNo& operator+= (const ComplexNo&);
// Accessor funcitions
// …..
// Mutator functions
// ….
// Other useful functionc
// ….
private:
double real, imaginary;
};
Main function:
We now ready to design our calculator dealing with complex numbers. When you switch on the calculator, you will see the following information displayed on the accumulator panel: see image.
To deal with an operation in calculator, we all know that we need to enter an operation followed by an operand (now our operand is a complex number). For example
+ 16 – 7i
* 2.3 + 4i
/ 88.9 – 6i
and ended with
=
The following shows some sample use of our complex number calculator: see image.
You can see from the above, partial results were displayed after each operation (highlighted after ==>. The calculator can identify invalid operation and division by zero. For your own pleasures, you can also add in more features like the recognitions of complex number format or set precision to the desired format.