Answer to Question #264884 in C++ for sam

Question #264884

Q#1). Define a class to represent a complex number called Complex. Provide the following member

functions:-

1. To assign initial values to the Complex object.

2. To display a complex number in a+ib format.

3. To add 2 complex numbers. (the return value should be complex)

4. To subtract 2 complex numbers

Write a main function to test the class.


1
Expert's answer
2021-11-12T17:35:49-0500
#include <iostream>


#include <string>


#include <sstream>
using namespace std;


class Complex{


private:
    double x;
    double y;


public:


    Complex() { 
        x = 0; 
        y = 0; 
        
    }






    Complex(double a, double b) { 
        x = a; 
        y = b; 
    }






    Complex operator + (Complex const& c1) {
        Complex result;
        result.x = x + c1.x;
        
        result.y = y + c1.y;
        
        return result;
    }






    Complex operator - (Complex const& c) {
    
    Complex result;
    result.x = x - c.x;
    
    result.y = y - c.y;
    
    return result;
    
    }






string display()


{


string result = "";






ostringstream a_sstream;


a_sstream << x;


string a_str = a_sstream.str();






ostringstream b_sstream;


b_sstream << y;


string b_str = b_sstream.str();






if (y < 0)


result = a_str + b_str + "i";


else


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






return result;


}


};




int main()


{


Complex c1(2.5, 4.1);
Complex c2(-3.4, -2.8);


Complex c3 = c1 + c2;
cout <<"Addition: "<< c3.display()<<endl;


Complex c4 = c1 - c2;
cout <<"Substraction: "<<c4.display()<<endl;


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