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

복소수 클래스

바로이순간 2013. 5. 4. 09:44

#include <iostream>

#include <string>

using namespace std;

class Complex {

    double real;

    double imag;

public:

    Complex();

    Complex(double a, double b);

    ~Complex();

    Complex add(const Complex& c);

    Complex subtract(const Complex& c);

    Complex multiply(const Complex& c);

    Complex divide(const Complex& c);

    void print();

};

Complex::Complex() {

    real =0;

    imag =0;

}

Complex::Complex(double a, double b) {

    real = a;

    imag = b;

}

Complex::~Complex() {

}

Complex Complex :: add(const Complex& c) {

    Complex temp;

    temp.real=this ->real +c.real;

    temp.imag=this ->imag + c.imag;

    return (temp);

}

Complex Complex :: subtract(const Complex& c) {

    Complex temp;

    temp.real=this ->real -c.real;

    temp.imag=this ->imag - c.imag;

    return (temp);

}

Complex Complex :: multiply(const Complex& c) {

    Complex temp;

    temp.real=this ->real*c.real-this->imag*c.imag;

    temp.imag=this ->real*c.imag+this->imag*c.real;

    return (temp);

}

Complex Complex :: divide(const Complex& c)

{

    Complex temp;

    temp.real=this ->real*c.real+this->imag*c.imag;

    temp.imag=this ->imag*c.real-this->real*c.imag;

    temp.real=temp.real/(c.real*c.real+c.imag*c.imag);

    temp.imag=temp.imag/(c.real*c.real+c.imag*c.imag);

    return (temp);

}

void Complex::print() {

    cout << real <<"+" <<imag << "i" <<endl;

}

int main(void) {

    Complex x(2, 3), y(4, 6), z;

    cout << "첫번째 복소수 x: ";

    x.print();

    cout << "두번째 복소수 y: ";

    y.print();

    z = x.add(y);

    cout << " z = x + y = ";

    z.print();

    z= x.subtract(y);

    cout << " z = x - y = ";

    z.print();

    z = x.multiply(y);

    cout << " z = x * y = ";

    z.print();

    z= x.divide(y);

    cout << " z = x / y = ";

    z.print();


    return(0);

}

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

확장된 애너그램 사전만들기  (0) 2013.07.24
c++ 입력오류 해결  (0) 2013.05.31
소인수 분해  (0) 2013.04.08
complex number class (복수수 클래스)  (0) 2012.12.08
스택 클래스  (0) 2012.11.05