Write a program in C++ that implements a simple arithmetic calculator using enumerator. Create
Operation enumerator with the elements (Add, Sub, Mul, Div). The function Calculate receives two
integer numbers and operation and returns the answer.
#include <iostream>
enum Operation {Add, Sub, Mul, Div};
int Calculator(int num1, int num2, Operation operation) {
switch (operation) {
case Add:
return num1 + num2;
case Sub:
return num1 - num2;
case Mul:
return num1 * num2;
case Div:
if (num2 == 0) return -1;
return num1 / num2;
}
}
// driver for testing
int main() {
int num1, num2;
std::cout << "Enter 2 numbers: ";
std::cin >> num1 >> num2;
int op;
std::cout << "Enter operation (1 - Add, 2 - Sub, 3 - Mul, 4 - Div): ";
std::cin >> op;
Operation operation;
if (op == 1) operation = Add;
else if (op == 2) operation = Sub;
else if (op == 3) operation = Mul;
else if (op == 4) operation = Div;
else {
std::cout << "Incorrect operation";
return 0;
}
int answer = Calculator(num1, num2, operation);
std::cout << "Answer = " << answer;
}
Comments
Leave a comment