// complex3.cpp // a class that models a complex number data type // a class that models a complex number data type #include #include //for getche() #include //for getche() class complex_number { private: float real; // real part float imaginary; // imaginery part float abs; // absolute value float arg; // argument public: void set() { char dummy; // for comma float a, b; cout << "Press i for Re + Im*j or press e for Abs*e^Arg: "; dummy = getche(); if (dummy == 'i') { cout << "\nEnter Re: "; cin >> real; cout << "Enter Im: "; cin >> imaginary; abs = sqrt(real*real + imaginary*imaginary); if (real != 0) if (real > 0) arg = atan(imaginary/real); else arg = atan(imaginary/real) + M_PI; else if (real > 0) arg = M_PI/2; else arg = -M_PI/2; } else { cout << "\nEnter Abs: "; cin >> abs; cout << "Enter Arg: "; cin >> arg; real = abs*cos(arg); imaginary = abs*sin(arg); } } // void set() void display() { cout << '(' << real // real part << " , " << imaginary // imaginary part << ')'; cout << " [" << abs // absolute value << " * e( i*" << arg // argument << " ) ]"; } void add(complex_number compl_num) { real += compl_num.real; imaginary += compl_num.imaginary; } void mult(complex_number compl_num) { complex_number cn; cn.real = real; cn.imaginary = imaginary; real = cn.real*compl_num.real - compl_num.imaginary*cn.imaginary; imaginary = cn.real*compl_num.imaginary + compl_num.real*cn.imaginary; } complex_number root_compl_num(int m, int n) { float phase = arg / n; complex_number root; root.abs = exp(log(abs)/n); root.arg = phase + m*2*M_PI/n; root.real = root.abs*cos(root.arg); root.imaginary = root.abs*sin(root.arg); return root; } }; // class complex_number void main() { complex_number c1; // create a complex_number variable complex_number c_roots[20]; // create an array of 20 complex_number variable int n; // enter c1 cout << "For c1, "; c1.set(); // set c1 // display c1 cout << "\nc1 = "; c1.display(); // enter the type of the root cout << "\nEnter root (n <= 20):"; cin >> n; cout << "\n=== The " << n << "th roots are ===\n"; // find n roots of c1 for (int i = 0; i < n; i++) { c_roots[i] = c1.root_compl_num(i, n); } // display n roots of c1 for (int i = 0; i < n; i++) { // show the i-th root cout << "\nroot[" << i + 1 << "] = "; c_roots[i].display(); // display c_root[i] } // stop the flow on the monitor getch(); } //end main