Skip to content

Instantly share code, notes, and snippets.

@bls1999
Last active June 14, 2022 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bls1999/4c8fc6caa59222c6921df2885e309092 to your computer and use it in GitHub Desktop.
Save bls1999/4c8fc6caa59222c6921df2885e309092 to your computer and use it in GitHub Desktop.
A small programming challenge for the purpose of learning C++.
#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