Answer to Question #329778 in C++ for zaira

Question #329778

Create a calculator for the complex number by creating a class of complex number (with two member variables, required constructor(s) and functions) with overloading all operators in it.(Operators: ++,--,+,-,/,*).

1
Expert's answer
2022-04-17T11:03:40-0400


#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>


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 tmp;
		tmp.real = real + 1;
		tmp.imag = imag;
		return tmp;
	}
	Complex operator- (Complex x)
	{
		Complex tmp;
		tmp.real = real - x.real;
		tmp.imag = imag - x.imag;
		return tmp;
	}
	Complex operator-- ()
	{
		Complex tmp;
		tmp.real = real - 1;
		tmp.imag = 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;
	}
	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()
{
	float a, ai;
	float b, bi;
	char ch;
	string choice;
	do
	{
		cout << "\nPlease, enter real and imaginary part of the first complex number:";
		cin >> a >> ai;
		cout << "Please, enter real and imaginary part of the second complex number:";
		cin >> b >> bi;
		Complex x(a, ai);
		Complex y(b, bi);
		cout << "Please, enter an operation from the following ++,--,+,-,/,*: ";
		cin >> choice;
		
		if (choice == "++")
			cout << (++x);
		else if(choice == "--")
			cout << (--x);
		else if (choice == "+")
			cout << (x+y);
		else if (choice == "-")
			cout << (x-y);
		else if (choice == "/")
			cout << (x / y);
		else if (choice == "*")
			cout << (x * y);
		cin.ignore(256, '\n');
		cout << "\nDo you want to continue? [Y/N]: ";
		cin >> ch;
	} while (ch=='Y');
}

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