// complex4.cpp // a class that models a complex number data type #include #include class complex_number { private: float real; // real part float imaginary; // imaginery part public: void set() { char dummy; // for comma cout << "Enter number (format Re, Im): "; cin >> real >> dummy >> imaginary; } void display() { cout << '(' << showpoint << setprecision(6) << real // real part << ',' << setprecision(6) << imaginary // imaginary part << ')'; } // add to the complex number another one (compl_num) complex_number add(complex_number compl_num) { complex_number cn; cn.real = real + compl_num.real; cn.imaginary = imaginary + compl_num.imaginary; return cn; } // subtract from the complex number another one (compl_num) complex_number sub(complex_number compl_num) { complex_number cn; cn.real = real - compl_num.real; cn.imaginary = imaginary - compl_num.imaginary; return cn; } // multiply two complex numbers and assign the result to third one complex_number mult(complex_number compl_num) { complex_number cn; cn.real = real*compl_num.real - imaginary*compl_num.imaginary; cn.imaginary = real*compl_num.imaginary + compl_num.real*imaginary; return (cn); } // divide the complex number by another one (compl_num) complex_number div(complex_number compl_num) { complex_number cn; cn.real = real; cn.imaginary = imaginary; float sqr_mod = compl_num.module(); if (sqr_mod == 0) { cout << "Devision by zero!" << endl; return cn; } sqr_mod *= sqr_mod; cn.real = (real*compl_num.real + compl_num.imaginary*imaginary)/sqr_mod; cn.imaginary = (compl_num.real*imaginary - real*compl_num.imaginary)/sqr_mod; return cn; } // calculate the module of the complex number float module() { float m = real*real + imaginary*imaginary; return sqrt(m); } }; // class complex_number void main() { // create three complex_number variables complex_number c1, c2, c3; char choice; do { // enter c1 cout << "For c1, "; c1.set(); // set c1 // enter c1 cout << "For c2, "; c2.set(); // set c2 // perform addition and ... c3 = c1.add(c2); // ... display the result c1.display(); cout << " + "; c2.display(); cout << " = "; c3.display(); cout << endl << endl; // perform subtraction and ... c3 = c1.sub(c2); // ... display the result c1.display(); cout << " - "; c2.display(); cout << " = "; c3.display(); cout << endl << endl; // perform multiplication and ... c3 = c1.mult(c2); // ... display the result c1.display(); cout << " * "; c2.display(); cout << " = "; c3.display(); cout << endl << endl; // perform division and ... c3 = c1.div(c2); // ... display the result c1.display(); cout << " + "; c2.display(); cout << " / "; c3.display(); cout << endl << endl; cout << "\nDo another (y/n)? "; cin >> choice; } while(choice != 'n'); } //end main