Division with the structure(Complex Numbers)

I wrote this code but the program gave an error.How can I fix my mistake?And how do I write this code with 'float mod' and 'float angle' ? Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  

  #include<iostream>
using namespace std;
struct complex{
	double re;
	double im;
};
complex div(complex z1,complex z2){
	complex z3;
	z3.re=((z1.re*z2.re)+(z1.im+z2.im))/((pow(z2.re,2))+(pow(z2.im,2)));
	z3.im=((z2.re*z1.im)-(z1.re*z2.im))/((pow(z2.re,2))+(pow(z2.im,2)));
	cout<<z3.re<<" "<<z3.im<<endl;
	return z3;
}
int main(){
	complex z1={6,3};
	complex z2={2,1};
	complex z3={0,0};
	z3=div(z1,z2);
	cout<<"Division"<<z3.re<<"  "<<z3.im<<endl;
	return 0;
}
I think the std::pow function is defined in the <cmath> standard header.
Also you could post the error for more help.

Edit:: BTW what do you mean by float mod and float angle?

Aceix.
Last edited on
You need to add #include <cmath> at the beginning of your code to use the pow() function. Also your code gives the wrong answer I believe.

Here is my implementation of complex numbers division:

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
#include <iostream>
#include <cmath>

struct complex
{
    float a; //The real part
    float b; //The imaginary part
};

complex divide(complex ab, complex cd)
{
    float real = ((ab.a*cd.a)+(ab.b*cd.b))/(pow(cd.a,2)+pow(cd.b,2));
    float imaginary = ((ab.b*cd.a)-(ab.a*cd.b))/(pow(cd.a,2)+pow(cd.b,2));
    complex ans = {real, imaginary};
    return ans;
}

int main()
{
    complex cmplx_1 = {2, 3};
    complex cmplx_2 = {4, -5};
    complex cmplx_3 = divide(cmplx_1, cmplx_2);
    
    if(cmplx_3.b > 0)
        std::cout << "Result: " << cmplx_3.a << "+" << cmplx_3.b << "i" << std::endl;
    else if(cmplx_3.b < 0)
        std::cout << "Result: " << cmplx_3.a << "-" << cmplx_3.b << "i" << std::endl;
    
    return 0;
}
Last edited on
Thank you very much for your help.And I have last question.How can I do if I wanted to divide into polar representation of complex numbers ? I think I'll write float angle and float mod but how can I write?
Well you might want to read this and implement it in C++:

http://en.wikipedia.org/wiki/Polar_coordinate_system#Complex_numbers

So first you have to make a function that converts the complex number to polar representation then make a division function that uses the formula for dividing complex numbers in polar form.

To get the angles, formulas on this page might be useful: http://www.mathportal.org/algebra/complex-numbers/complex-numbers-polar-representation.php
Last edited on
Topic archived. No new replies allowed.