Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

c++ (Complex Class) #include <iostream> #include <iomanip> #include <string> #in

ID: 3685764 • Letter: C

Question

c++

(Complex Class)

#include <iostream>

#include <iomanip>

#include <string>

#include <algorithm>

using namespace std;

void stretch2();

class Complex

{

private:

double real;

double imag;

public:

Complex() : real(0)

, imag(0)

{};

void input(std::istream&)

{

cin >> real;

cin >> imag;

};

void output(std::ostream&)

{

cout << fixed << setprecision(1) << real << " + " << fixed << setprecision(1) << imag << "i";

};

double getReal()

{

return real;

};

double getImag()

{

return imag;

};

void setReal(double r)

{

real = r;

};

void setImag(double i)

{

imag = i;

};

};

int main()

{

//srand(static_cast<unsigned int>(time(nullptr)));

stretch2();

return 0;

}

void stretch2()

{

Complex c1;

Complex c2;

cout << "Enter values for real and imaginary coefficients: ";

c1.input(cin);

cout << "Enter values for real and imaginary coefficients: ";

c2.input(cin);

c1.output(cout);

cout << endl;

c2.output(cout);

cout << endl;

double temp;

cout << "Enter a new value for the real coefficient: ";

cin >> temp;

c2.setReal(temp);

cout << "The new real coefficient is " << c2.getReal() << endl;

c2.output(cout);

cout << endl;

}

Explanation / Answer

#include <iostream>

using namespace std;


class complex {
private:
double Re, Im;

public:
complex() : Re(0.0), Im(0.0) {}
complex(double Re, double Im) : Re(Re), Im(Im) {}
double getRe() const { return Re; }
double getIm() const { return Im; }
friend complex operator+(const complex&, const complex&);
friend istream &operator>>( istream & , complex& );
friend ostream& operator<<(ostream &, const complex&);
friend complex operator~(const complex&);
};
  
complex operator~(const complex& a)
{
double r,i;
r = a.getRe() * -1;
i = a.getIm() * -1;
return complex(r,i);

}

complex operator+(const complex& a, const complex& b)
{
double r, i;
r = a.getRe() + b.getRe();
i = a.getIm() + b.getIm();
return complex(r, i);
}

ostream& operator<<(ostream& out, const complex &a)
{
out << "(" << a.getRe() << ", " << a.getIm() << ")" << endl;
return out;
}

istream &operator>>(istream &in, complex &c) //input
{
cout<<" enter real part: ";
in>>c.Re;
cout<<"enter imag part: ";
in>>c.Im;
return in;
}

int main(void) {
complex c1,c2,c3;
cout << "Enter two complex values: ";
cin >> c1 >> c2;
c3 = c1 + c2;
cout << "The sum is : " << c3 << endl;
cout << "and negating the sum yields: " << ~c3 << endl;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote