(C++ with comments where possible) Define a class for complex numbers. A complex
ID: 3774580 • Letter: #
Question
(C++ with comments where possible) Define a class for complex numbers. A complex number is a number of the form a + b*i where for our purposes, a and b are numbers of type double, and i is a number that represents the quantity sqrt(-1). Represent a complex number as two values of type double. Name the member variables real and imaginary. (The variable for the number that is multiplied by i is the one called imaginary.) Call the class Complex. Include a constructor with two parameters of type double that can be used to set the member variables of an object to any values. Include a constructor that has only a single parameter of type double; call this parameter realPart and define the constructor so that the object will be initialized to realPart + 0*i. Include a default constructor that initializes an object to 0(that is, to 0 + 0*i). Overload all the following operators so that they correctly apply to the type Complex: ==, +, -, *, >>, and <<. You should also write a test program to test your class. In the interface file, you should define a constant i as follows: const Complex i(0,1);
Explanation / Answer
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
class complex
{
int i,r;
public:
void read()
{
cout<<" Enter Real Part:";
cin>>r;
cout<<"Enter Imaginary Part:";
cin>>i;
}
void display()
{
cout<<" = "<<r<<"+"<<i<<"i";
}
complex operator+(complex a2)
{
complex a;
a.r=r+a2.r;
a.i=i+a2.i;
return a;
}
complex operator-(complex a2)
{
complex a;
a.r=r-a2.r;
a.i=i-a2.i;
return a;
}
complex operator*(complex a2)
{
complex a;
a.r=(r*a2.r)-(i*a2.i);
a.i=(r*a2.i)+(i*a2.r);
return a;
}
complex operator/(complex a2)
{
complex a;
a.r=((r*a2.r)+(i*a2.i))/((a2.r*a2.r)+(a2.i*a2.i));
a.i=((i*a2.r)-(r*a2.i))/((a2.r*a2.r)+(a2.i*a2.i));
return a;
}
};
void main()
{
int ch;
clrscr();
complex a,b,c;
do
{
cout<<" 1.Addition 2.Substraction";
cout<<" 3.Mulitplication 4.Division 5.Exit ";
cout<<" Enter the choice :";
cin>>ch;
switch(ch)
{
case 1:
cout<<" Enter The First Complex Number:";
a.read();
a.display();
cout<<" Enter The Second Complex Number:";
b.read();
b.display();
c=a+b;
c.display();
break;
case 2:
cout<<" Enter The First Complex Number:";
a.read();
a.display();
cout<<" Enter The Second Complex Number:";
b.read();
b.display();
c=b-a;
c.display();
break;
case 3:
cout<<" Enter The First Complex Number:";
a.read();
a.display();
cout<<" Enter The Second Complex Number:";
b.read();
b.display();
c=a*b;
c.display();
break;
case 4:
cout<<" Enter The First Complex Number:";
a.read();
a.display();
cout<<" Enter The Second Complex Number:";
b.read();
b.display();
c=a/b;
c.display();
break;
}
}while(ch!=5);
getch();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.