From 23d1ea1faa9c1c6b8f5f08f2fb6e0fe47ee14796 Mon Sep 17 00:00:00 2001 From: Micke Nordin Date: Sat, 18 Apr 2020 11:16:20 +0200 Subject: [PATCH] Add division --- cnumber.cpp | 10 ++++++++-- cnumber.hpp | 28 ++++++++++++++++++++++++---- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/cnumber.cpp b/cnumber.cpp index 068e724..33e8818 100644 --- a/cnumber.cpp +++ b/cnumber.cpp @@ -3,15 +3,21 @@ int main() { - cnumber a(1, -3); - cnumber b(2, 5); + cnumber a(3,2); + cnumber b(4,-3); cout << "a = " << a << endl; cout << "a* = " << a.conjugate() << endl; + cout << "a*a* = " << a * a.conjugate() << endl; cout << "b = " << b << endl; cout << "b* = " << b.conjugate() << endl; + cout << "b*b* = " << b * b.conjugate() << endl; cout << "a + b = " << a + b << endl; cout << "(a + b)* = " << (a + b).conjugate() << endl; + cout << "a - b = " << a - b << endl; + cout << "(a - b)* = " << (a - b).conjugate() << endl; cout << "a * b = " << a * b << endl; cout << "(a * b)* = " << (a * b).conjugate() << endl; + cout << "a / b = " << a / b << endl; + cout << "(a / b)* = " << (a / b).conjugate() << endl; } diff --git a/cnumber.hpp b/cnumber.hpp index 09e7e79..d289e33 100644 --- a/cnumber.hpp +++ b/cnumber.hpp @@ -4,7 +4,7 @@ using namespace std; class cnumber { private: - int r, i; + float r, i; bool signr, signi; bool get_sign(int i) { return (i >= 0); @@ -18,9 +18,23 @@ class cnumber { signr = get_sign(r); signi = get_sign(i); + } + cnumber(float a, float b) { + r = a; + i = b; + signr = get_sign(r); + signi = get_sign(i); + + } + cnumber(const cnumber &z) { + r = z.r; + i = z.i; + signr = z.signr; + signi = z.signi; + } // Member functions - cnumber conjugate() { + cnumber conjugate() const { cnumber z(this->r, this->i * -1); return z; } @@ -36,14 +50,20 @@ class cnumber { return z; } cnumber operator*(const cnumber &that) { - cnumber z( (that.r * this->r ) - (that.i * this->i) , (that.r * this->i) + (this->r * that.i) ); + cnumber z( (this->r * that.r ) - (this->i * that.i) , (this->r * that.i) + (that.r * this->i) ); return z; } + cnumber operator/(const cnumber &that) { + cnumber numerator( (this->r * that.r ) - (this->i * ( that.i * -1)) , (this->r * (that.i * -1)) + (that.r * this->i) ); + cnumber denominator( (that.r * that.r ) - (that.i * ( that.i * -1)) , (that.r * (that.i * -1)) + (that.r * that.i) ); + cnumber ratio(numerator.r / denominator.r, numerator.i / denominator.r); + return ratio; + } friend ostream &operator<<( ostream &os, const cnumber &z ) { if (z.r != 0) { os << z.r; - if (z.signi && (z.i != 0)) { + if (z.signi && (z.i > 0)) { os << '+'; } }