Complex numbers can be represented in polar form like M<θ. Where M is the magnitude and
θ is the angle in degrees. Use the concept of operator overloading to write a class in which the
user will enter the magnitudes and angles (in degrees) for two complex numbers. And then
the program will add, subtract, divide or multiply them and display the result in polar form.
#include <iostream>
#include <cmath>
using namespace std;
const double PI=3.1415926;
class Complex {
double mag;
double theta;
public:
Complex(double m, double th) : mag(m), theta(th) {}
Complex operator+(const Complex& a) const;
Complex operator-(const Complex& a) const;
Complex operator*(const Complex& a) const;
Complex operator/(const Complex& a) const;
void print(ostream& os) const;
};
Complex Complex::operator+(const Complex& a) const
{
double x = mag * cos(theta);
double y = mag * sin(theta);
x += a.mag * cos(a.theta);
y += a.mag * sin(a.theta);
double m = sqrt(x*x + y*y);
double th = atan2(y, x);
return Complex(m, th);
}
Complex Complex::operator-(const Complex& a) const
{
double x = mag * cos(theta);
double y = mag * sin(theta);
x -= a.mag * cos(a.theta);
y -= a.mag * sin(a.theta);
double m = sqrt(x*x + y*y);
double th = atan2(y, x);
return Complex(m, th);
}
Complex Complex::operator*(const Complex& a) const
{
double m = mag * a.mag;
double th = theta + a.theta;
if (th > PI)
th -= PI;
if (th < -PI)
th += PI;
return Complex(m, th);
}
Complex Complex::operator/(const Complex& a) const
{
if (a.mag == 0.0)
return Complex(0, 0);
double m = mag / a.mag;
double th = theta - a.theta;
if (th > PI)
th -= PI;
if (th < -PI)
th += PI;
return Complex(m, th);
}
void Complex::print(ostream& os) const
{
os << mag << "<" << theta;
}
ostream& operator<<(ostream& os, const Complex& z)
{
z.print(os);
return os;
}
int main()
{
double m, th;
cout << "Enter first complex number z1" << endl;
cout << "magnitude: ";
cin >> m;
cout << "Theta: ";
cin >> th;
Complex z1(m, th);
cout << "Enter second complex number z2" << endl;
cout << "magnitude: ";
cin >> m;
cout << "Theta: ";
cin >> th;
Complex z2(m, th);
cout << "z1 + z2 = " << z1 + z2 << endl;
cout << "z1 - z2 = " << z1 - z2 << endl;
cout << "z1 * z2 = " << z1 * z2 << endl;
cout << "z1 / z2 = " << z1 / z2 << endl;
}
Comments
Leave a comment