Answer to Question #323911 in C++ for megha

Question #323911

Develop a C++ class named Complex

Complex to hold complex numbers data. The class should support functionality to support computation of complex conjugate, magnitude, phase and to print the number in format x+i(y)

x+i(y) where x

x is real and y

y is imaginary part. Provide at least three (default, copy and set by values) constructors.

Also, overload the four basic arithmetic operators(+, -, *, /) and write code to use those implementations. 


1
Expert's answer
2022-04-05T09:30:26-0400
#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

class Complex
{
	float real;
	float imag;
public:
	Complex():real(0),imag(0){}
	Complex(float _real,float _imag)
	:real(_real),imag(_imag){}
	Complex(Complex& x):real(x.real),imag(x.imag){}
	Complex operator+ (Complex x)
	{
		Complex tmp;
		tmp.real = real + x.real;
		tmp.imag = imag + x.imag;
		return tmp;
	}
	Complex operator- (Complex x)
	{
		Complex tmp;
		tmp.real = real - x.real;
		tmp.imag = imag - x.imag;
		return tmp;
	}
	Complex operator* (Complex x)
	{
		Complex tmp;
		tmp.real = (real*x.real)-(imag*x.imag);
		tmp.imag = (real*x.imag)-(imag*x.real);
		return tmp;
	}
	Complex operator/ (Complex x)
	{
		Complex tmp;
		float div = (x.real*x.real) + (x.imag*x.imag);
		tmp.real = (real*x.real) + (imag*x.imag);
		tmp.real /= div;
		tmp.imag = (real*x.imag) - (imag*x.real);
		tmp.imag /= div;
		return tmp;
	}
	Complex conjugate()
	{
		Complex tmp;
		tmp.real = real;
		tmp.imag = imag* -1;
		return tmp;
	}
	float magnitude()
	{
		float z;
		z = (real*real) + (imag*imag);
		z = sqrt(z);
		return z;
	}
	float phase() { return atan2(real, imag);}
	friend ostream& operator<< (ostream& os, Complex& x);
};

ostream& operator<< (ostream& os, Complex& x)
{
	os << x.real << setiosflags(ios::showpos) << x.imag << "i"
		<< resetiosflags(ios::showpos);
	return os;
}

int main()
{
	Complex a(10, 12);
	cout << a << endl;
	Complex b(a);
	cout << b << endl;
	cout << "Conugate a: ";
	Complex c = a.conjugate();
	cout << c << endl;
	cout << "Magnitude a: ";
	cout << a.magnitude() << endl;
	cout << "Phase a: ";
	cout << a.phase() << endl;
	Complex d(4, -6);
	cout << d << endl;
	cout << "a+d: ";
	Complex e = a + d;
	cout << e << endl;
	cout << "a-d: ";
	e = a - d;
	cout << e << endl;
	cout << "a*d: ";
	e = a * d;
	cout << e << endl;
	cout << "a/d: ";
	e = a / d;
	cout << e << endl;
}



Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS