Answer to Question #101984 in C++ for Fardeen Shaikh

Question #101984
Define a class named Complex for representing complex numbers. A complex number has the general form a + ib, where a- the real part, b - the imaginary part are both real numbers and i2=-1. Define parameterized and default constructor. Overload binary + and - operators with usual meaning.
1
Expert's answer
2020-01-29T08:05:56-0500

#include <iostream>

#include <string>

#include <sstream>


class Complex

{

private:

double a,

b;


public:

Complex() { a = 0; b = 0; }


Complex(double a, double b) { this->a = a; this->b = b; }


Complex operator + (Complex const& obj) {

Complex res;


res.a = a + obj.a;

res.b = b + obj.b;


return res;

}


Complex operator - (Complex const& obj) {

Complex res;


res.a = a - obj.a;

res.b = b - obj.b;


return res;

}


std::string print()

{

std::string result = "";


std::ostringstream a_sstream;

a_sstream << a;

std::string a_str = a_sstream.str();


std::ostringstream b_sstream;

b_sstream << b;

std::string b_str = b_sstream.str();


if (b < 0)

result = a_str + b_str + "i";

else

result = a_str + "+" + b_str + "i";


return result;

}

};


//example of use

int main()

{

Complex num1(2.5, 4.1),

num2(-3.4, -2.8);


Complex num3 = num1 - num2;


std::cout << num3.print();


return 0;

}


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