Objective: Introduce students to object oriented programming, to write classes t
ID: 3915798 • Letter: O
Question
Objective: Introduce students to object oriented programming, to write classes to test classes. and test programs Laboratory: Program: Create a class called complex performing arithmetic with complex numbers. Write a program to test your class. Complex numbers have the form: realPart+imaginaryPart *i Where i is O-1 Use double variables to represent data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initializers are provided. Provide public member functions for each of the following a. Adding two complex numbers. The real parts are added together and the imaginary parts are added together b. Subtracting two complex numbers. The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of the left operand. e. Printing complex numbers in the form (a, b), where a is the real part and b is the imaginary part. Create a source file for your program, compile it, execute it, and show results to your instructor.Explanation / Answer
Solution
#include <iostream>
#include <iomanip>
using namespace std;
class Complex
{public:
void displayComplex();
Complex(double,double);
Complex add(Complex x);
Complex subtract(Complex x);
private:
double real,imag;
};
Complex::Complex(double r=0,double i=0)
{real=r;
imag=i;
}
Complex Complex::add(Complex x)
{Complex temp;
temp.real=real+x.real;
temp.imag=imag+x.imag;
return(temp);}
Complex Complex::subtract(Complex x)
{Complex temp;
temp.real=real-x.real;
temp.imag=imag-x.imag;
return(temp);}
void Complex::displayComplex(void)
{cout<<fixed<<setprecision(2)<<"("<<real<<","<<imag<<")";
}
int main()
{double r,i;
cout<<"Enter real part: ";
cin>>r;
cout<<"enter imaginary part: ";
cin>>i;
Complex a(r,i),b(9,2),c;
Complex d(10,1),e(11,5);
c=a.add(b);
a.displayComplex();
cout<<" + ";
b.displayComplex();
cout<<" = ";
c.displayComplex();
cout<<endl;
c=d.subtract(e);
d.displayComplex();
cout<<" - ";
e.displayComplex();
cout<<" = ";
c.displayComplex();
cout<<endl;
system("pause");
return 0;
}
Feel free to reach out regarding any queries . And please do rate the answer . Thank you .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.