In: Computer Science
Problem 2 (C++):
Design and implement a class complexType, that can be used to process complex numbers.
A number of the form a +ib, in which i2 = -1 and a and b are real numbers, is called a complex number. We call a the real part and b the imaginary part of a + ib.
Complex numbers can also be represented as ordered pairs (a, b).
The class you will design should have the following features.
Constructor
Your class should have a default constructor as well as a parametrized constructor (which requires 2 double arguments).
Accessor functions required
Your class should implement the following member functions:
setComplex – set the real and imaginary parts of the complex number
getComplex – get the real and imaginary parts complex number
Operator Overloading
The class must overload and implement the following operators:
Stream I/O
To output a complex number in the form (a, b)
in which a is the real part and b is the imaginary part, the algorithm is as follows:
The algorithm to read this complex number is as follows:
If (a, b) and (c, d) are complex numbers:
(a, b) + (c, d) = (a + c, b + d)
(a, b) - (c, d) = (a - c, b - d)
If (a, b) and (c, d) are complex numbers:
((a, b) * (c, d) = ac +ad + bc +bd
If (c, d) is nonzero:
(a, b)/(c, d)=((ac +bd)/(c2 +d2 ), (-ad +bc)/( c2 +d2))
C++ code
#include<iostream>
using namespace std;
class complexType{
private:
double real,imag;
public:
complexType(){
real = 0;
imag = 0;
}
complexType(double r , double
i){
real = r;
imag = i;
}
void setReal(double r){
real = r;
}
void setImag(double i){
imag = i;
}
double getReal(){
return
real;
}
double getImag(){
return
imag;
}
complexType& operator+(const
complexType& other){
double r = real
+ other.real;
double i = imag
+ other.imag;
return *(new
complexType(r , i));
}
complexType& operator-(const
complexType& other){
double r = real
- other.real;
double i = imag
- other.imag;
return *(new
complexType(r , i));
}
complexType& operator*(const
complexType& other){
double r = real
* other.real - imag*other.imag;
double i =
imag*other.real + real*other.imag;
return *(new
complexType(r , i));
}
complexType& operator/(const
complexType& other){
double val =
(other.real* other.real + other.imag*other.imag);
double r = (real
* other.real + imag*other.imag)/val;
double i =
(imag*other.real - real*other.imag)/val;
return *(new
complexType(r , i));
}
friend ostream& operator
<< (ostream& out , const complexType& other){
out<<"("<<other.real<<",
"<<other.imag<<")";
return
out;
}
friend istream& operator
>> (istream& in , complexType& other){
char ch;
in>>ch>>other.real>>ch>>other.imag>>ch;
return in;
}
};
int main(){
complexType c1(2,3);
complexType c2,c3;
cin>>c2;
c3 = c1 + c2;
cout<<"c1 + c2 = "<<c3<<endl;
c3 = c1 - c2;
cout<<"c1 - c2 = "<<c3<<endl;
c3 = c1 * c2;
cout<<"c1 * c2 = "<<c3<<endl;
c3 = c1 / c2;
cout<<"c1 / c2 = "<<c3<<endl;
return 0;
}