In: Computer Science
Create a class for working with complex numbers. Only 2 private float data members are needed, the real part of the complex number and the imaginary part of the complex number. The following methods should be in your class:a. A default constructor that uses default arguments in case no initializers are included in the main.b. Add two complex numbers and store the sum.c. Subtract two complex numbers and store the difference.d. Multiply two complex numbers and store the product.e. Print a complex number in the form a + bi or a – bi where a is the real part of the complex number and b is the imaginary part of the complex number. For example, 4 + 5i, 3 + 0i, 0 + 4if. Change a complex number to its cube. Your main should instantiate two complex numbers and call each of the class methods. The two complex numbers should be printed along with the sum, difference, and product of the two complex numbers. Lastly, print the cubes of the two complex numbers. (Please do not overload the operators for this program.)
This is for C++
Try this once:
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex(float r = 0, float i = 0):real(r),imag(i){};
void setComplex(void)
{
cout << "Enter the real and imaginary parts : ";
cin >> this->real;
cin >> this->imag;
}
Complex add(const Complex& c)
{
Complex comp;
comp.real = this->real + c.real;
comp.imag = this->imag + c.imag;
return comp;
}
Complex subtract(const Complex& c)
{
Complex comp;
comp.real = this->real - c.real;
comp.imag = this->imag - c.imag;
return comp;
}
Complex multiply(const Complex&c)
{
Complex comp;
comp.real=this->real*c.real;
comp.imag=this->imag*c.imag;
return comp;
}
void square()
{
float temp=this->real;
this->real=this->real*this->real-this->imag*this->imag;
this->imag=2*this->imag*temp;
}
cout << "Setting first complex number " <<
endl;
a.setComplex();
cout << "Setting second complex number " << endl;
b.setComplex();
/* Adding two complex numbers */
cout << "Addition of a and b : " << endl;
c = a.add(b);
c.printComplex();
/* Subtracting two complex numbers */
cout << "Subtraction of a and b : " << endl;
d = a.subtract(b);
d.printComplex();
/* Multiplication two complex numbers */
cout << "Multiplication of a and b : " << endl;
e = a.multiply(b);
e.printComplex();
/*change the complex number to its square*/
cout << "Changing complex number a to its square: " <<
endl;
a.square();
a.printComplex();
}