Last active
June 14, 2022 23:40
-
-
Save bls1999/4c8fc6caa59222c6921df2885e309092 to your computer and use it in GitHub Desktop.
A small programming challenge for the purpose of learning C++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class ComplexNumber { | |
public: | |
double real; | |
double imag; | |
ComplexNumber(double r, double i) { | |
real = r; | |
imag = i; | |
} | |
void print() { | |
cout << endl << "Result: " << endl << " Real: " << real << endl << " Imaginary: " << imag << endl; | |
} | |
ComplexNumber operator+(ComplexNumber cn2) { | |
return ComplexNumber(this->real + cn2.real, this->imag + cn2.imag); | |
} | |
ComplexNumber operator-(ComplexNumber cn2) { | |
return ComplexNumber(this->real - cn2.real, this->imag - cn2.imag); | |
} | |
ComplexNumber operator*(ComplexNumber cn2) { | |
return ComplexNumber(this->real * cn2.real, this->imag * cn2.imag); | |
} | |
ComplexNumber operator/(ComplexNumber cn2) { | |
return ComplexNumber(this->real / (double) cn2.real, this->imag / (double) cn2.imag); | |
} | |
}; | |
int main() { | |
cout << endl << "-- Calculator --" << endl << endl; | |
double x1, y1, x2, y2; | |
cout << "Enter the first complex number: " << endl; | |
cout << "Enter real: "; | |
cin >> x1; | |
cout << "Enter imaginary: "; | |
cin >> y1; | |
cout << "Enter the second complex number: " << endl; | |
cout << "Enter real: "; | |
cin >> x2; | |
cout << "Enter imaginary: "; | |
cin >> y2; | |
ComplexNumber cn1(x1, y1); | |
ComplexNumber cn2(x2, y2); | |
cout << endl << "Thank you." << endl << endl; | |
while (true) { | |
cout << "(1) Add" << endl << "(2) Subtract" << endl << "(3) Multiply" << endl << "(4) Divide" << endl << "Enter the number of the operation you'd like to perform: "; | |
int op; | |
cin >> op; | |
string result = ""; | |
switch (op) { | |
case 1: | |
(cn1 + cn2).print(); | |
break; | |
case 2: | |
(cn1 - cn2).print(); | |
break; | |
case 3: | |
(cn1 * cn2).print(); | |
break; | |
case 4: | |
(cn1 / cn2).print(); | |
break; | |
default: | |
cout << "Error: You must enter a valid number for the desired operation (1-4)." << endl << endl; | |
continue; | |
} | |
break; | |
} | |
cout << endl << "Thanks for using the calculator!" << endl << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment