c·c++/c++ 프로그래밍

complex number class (복수수 클래스)

바로이순간 2012. 12. 8. 12:42

#include <iostream>

using namespace std;


class ComplexNumber {

  public:

    ComplexNumber(double re = 0.0, double im = 0.0) : real(re), imag(im)  {   }

    double getReal();

    double getImag();

    void setReal(double);

    void setImag(double);

    friend ComplexNumber operator+ (const ComplexNumber &a, const ComplexNumber &b);

    friend ComplexNumber operator- (const ComplexNumber &a, const ComplexNumber &b);

    friend ComplexNumber operator* (const ComplexNumber &a, const ComplexNumber &b);

    friend ComplexNumber operator/ (const ComplexNumber &a, const ComplexNumber &b);


    friend ostream&      operator<<(ostream &out, const ComplexNumber &c);


  private:

    double real;

    double imag;

};


double ComplexNumber::getReal() {

  return real;

}


double ComplexNumber::getImag() {

  return imag;

}


void ComplexNumber::setReal(double re) {

  real=re;

}


void ComplexNumber::setImag(double im) {

  imag=im;

}


ComplexNumber operator+ (const ComplexNumber &a, const ComplexNumber &b) {

  ComplexNumber result;


  result.real = a.real + b.real;

  result.imag = a.imag + b.imag;


  return result;

}


ComplexNumber operator- (const ComplexNumber &a, const ComplexNumber &b) {

  ComplexNumber result;


  result.real = a.real - b.real;

  result.imag = a.imag - b.imag;


  return result;

}


ComplexNumber operator* (const ComplexNumber &a, const ComplexNumber &b) {

  ComplexNumber result;


  result.real = (a.real * b.real - a.imag * b.imag);

  result.imag = (a.real * b.imag + a.imag * b.real);


  return result;

}


ComplexNumber operator/ (const ComplexNumber &a, const ComplexNumber &b) {

  ComplexNumber result;


  result.real = (a.real * b.real + a.imag * b.imag) / (b.real * b.real + b.imag * b.imag);

  result.imag = (a.imag * b.real - a.real * b.imag) / (b.real * b.real + b.imag * b.imag);


  return result;

}


ostream& operator<< (ostream &out, const ComplexNumber &c) {

  out << c.real << "+" << c.imag << "i";

  return out;

}


int main () {

  ComplexNumber x(1, 2), y, z;

  ComplexNumber sum, difference, product, quotient;


  y = ComplexNumber(2, 4);


  z = ComplexNumber(3, 0);


  cout << "x is:  " << x << endl;

  cout << "y is:  " << y << endl;

  cout << "z is:  " << z << endl;


  cout << "x real="<<x.getReal()<<" x imag="<<x.getImag()<<endl;


  sum        = x + y;

  difference = x - y;

  product    = x * y;

  quotient   = sum / z;

  cout << "The sum (x + y) is:  " << sum << endl;

  cout << "The difference (x - y) is:  " << difference<< endl;

  cout << "The product (x * y) is:  " << product << endl;

  cout << "The quotient (sum / z) is:  " << quotient << endl;


  return 0;

}

'c·c++ > c++ 프로그래밍' 카테고리의 다른 글

복소수 클래스  (0) 2013.05.04
소인수 분해  (0) 2013.04.08
스택 클래스  (0) 2012.11.05
다항식의 곱셈  (0) 2012.09.24
조건을 가진 확률분포  (0) 2012.09.16