创建复数类实现复数运算
#include<iostream> using namespace std; class Complex { double real; double image; public: Complex() { real = 0; image = 0; } Complex(int r, int i) { real = r; image = i; } Complex Add(Complex&); Complex Sub(Complex&); Complex Multi(Complex&); void dispay() { if (real == 0) cout << image << "i" << endl; else if (real != 0 && image == 0) cout << real << endl; else if (real != 0 && image < 0) cout << real << image << "i" << endl; else cout << real << "+" << image << "i" << endl; } }; Complex Complex::Add(Complex& c2) { Complex c; c.real = this->real + c2.real; c.image = this->image + c2.image; return c; } Complex Complex::Sub(Complex& c2) { Complex c; c.real = this->real - c2.real; c.image = this->image - c2.image; return c; } Complex Complex::Multi(Complex& c2) { Complex c; c.real = this->real * c2.real - this->image * c2.image; c.image = this->real * c2.image + this->image * c2.real; return c; } int main() { Complex c1(1, 2); Complex c2(2, 3); Complex temp; temp=c1.Add(c2); temp.dispay(); temp = c1.Multi(c2); temp.dispay(); temp = c1.Sub(c2); temp.dispay(); return 0; }
遇到问题:
要考虑实部为零,虚部为零,虚部为负这几个情况