From e15b4bc64b0ae895482886872c2b3d6f2c6d740b Mon Sep 17 00:00:00 2001 From: 4bh1n4v <54211410+4bh1n4v@users.noreply.github.com> Date: Thu, 1 Oct 2020 02:49:37 +0530 Subject: [PATCH] I faced this question during my oops labs, maybe you could add this to prac folder so if anybody else needs it might be helpful A complex number x + iy is a number which has 2 parts - a real part (x) and an imaginary part (y). Write a C++ program that simulates a complex number as an object. Assume both x and y are integers. The user should be able to do the following operations on these complex number objects: a) Addition of 2 complex numbers by writing the code: c3 = c1+c2 b) Multiplying c1 and c2 and storing the result in c1 using the code: c1 *= c2 c) Overload a type casting operator that allows implicit / explicit type casting of a complex number object to a float variable as follows: float x; x=c1; // where c1 is a complex number object For example, i) If c1 = 10+6i, then x will store 10.6 ii) If c1 = 5+22i, then x will store 5.22 --- Q1.cpp | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Q1.cpp diff --git a/Q1.cpp b/Q1.cpp new file mode 100644 index 0000000..038ab86 --- /dev/null +++ b/Q1.cpp @@ -0,0 +1,60 @@ +#include +using namespace std; + +class Complex +{ public: + int real; + int imag; + + Complex()//default constructor + { this->real=0; + this->imag=0; + } + Complex(int real, int imag)//making a complex number + { this->real=real; + this->imag=imag; + } + Complex operator + (Complex const &b)//add 2 complex numbers + { Complex c; + c.real=real+b.real; + c.imag=imag+b.imag; + return c; + } + Complex& operator * (Complex const &b)//multiply 2 complex numbers + { int temp; + temp=((real * b.real)-(imag * b.imag)); + imag=((real * b.imag)+(imag * b.real)); + real=temp; + return *this; + } + operator float() const//cast into float form as per c part + { float i=0; + float s=real/abs(real); + i+=abs(real); //real part will retain it's sign that is -4+2i will become -4.2 + if(imag==0) + return i*s; + + int digits =log10(abs(imag))+1;//incase imaginary part is negative we will ignore that like for 2-3i we will show 2.3 + float temp=(float)(abs(imag))/(float)pow(10,digits);//incase imaginary part has zero behind it, we will ommit them like for 2+10i we will show 2.1 + i+=temp; + return i*s; + } +}; + +int main() +{ int x1,y1,x2,y2; + cout<<"Enter Real and Imaginary parts of the first Complex Number : "; + cin>>x1>>y1; + cout<<"\nEnter Real and Imaginary parts of the second Complex Number : "; + cin>>x2>>y2; + Complex a(x1,y1); + Complex b(x2,y2); + Complex c=a+b; + Complex t=a; + a =a* b; + cout<<"a.) Result for Addition = "<