operator overload
I have the following:
class Complex
{
public:
Complex();
Complex(int r, int i);//r:real part i:imaginary part
void printComplex();
Complex operator/(Complex c);
double real;
double imag;
};
Complex::Complex(int r,int i):real(r),imag(i){}
Complex Complex::operator/(Complex c)//(a+ib)/(c+id)=(ac+bd+i(bc-ad))/(c^2+d^2)
{
Complex div;
div.real=((real*c.real)+(imag*c.imag))/(c.real*c.real)+(c.imag*c.imag);
div.imag=((imag*c.real)-(real*c.imag))/(c.real*c.real)+(c.imag*c.imag);
return div;
}
void Complex::printComplex()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
int main(){
Complex c1(1,2), c2(5,7);
Complex c6 = c1 / c2;
cout << "c1 / c2: ";
c6.printComplex();
} |
If i print separetely
((real*c.real)+(imag*c.imag)) |
I get 19
On
(c.real*c.real)+(c.imag*c.imag); |
I get 74
but the division of the two elements gives me 49.76 and not 0.256 as expected. Why is that?
The first refers to this->real and this->imag, and the second refers to c.real and c.imag.
Next time use [code]. It took me two more minutes than necessary to understand what the hell was going on.
Thanks for your efforts.So how should it be, in order to get proper result?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream.h>
class Complex
{
public:
Complex();
Complex(int r, int i);//r:real part i:imaginary part
void printComplex();
Complex operator/(Complex c);
double real;
double imag;
};
Complex::Complex():real(0),imag(0){}
Complex::Complex(int r,int i):real(r),imag(i){}
Complex Complex::operator/(Complex c) //(a+ib)/(c+id)=(ac+bd+i(bc-ad))/(c^2+d^2)
{
Complex div;
div.real=((real*c.real)+(imag*c.imag))/((c.real*c.real)+(c.imag*c.imag));
div.imag=((imag*c.real)-(real*c.imag))/((c.real*c.real)+(c.imag*c.imag));
return div;
}
void Complex::printComplex()
{
cout<<real<<" + "<<imag<<"i"<<endl;
}
int main()
{
Complex c1(1,2), c2(5,7);
Complex c6 = c1/c2;
cout << "c1 / c2: ";
c6.printComplex();
return 0;
}
|
I included an additional pair of brackets in the formula.
You did not define your default constructor !
Main should be returning a value!
And yeah,
INDENT YOR CODE and use the code tags !
Topic archived. No new replies allowed.