Created
March 6, 2023 20:57
-
-
Save timsonner/9b6e8401888de1b716f256fa17914264 to your computer and use it in GitHub Desktop.
C++. Calculator. Usage of namespace and switch statements.
This file contains hidden or 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 std::cin; | |
| using std::cout; | |
| using std::endl; | |
| // Define a top-level namespace for the calculator | |
| namespace calculator { | |
| // Define a nested namespace for the functions | |
| namespace functions { | |
| char operand; | |
| double num1; | |
| double num2; | |
| double result; | |
| bool valid; // a flag to indicate if the operand is valid | |
| void getUserInput() | |
| { | |
| cout << "Enter an operand: "; | |
| cin >> operand; | |
| if(!valid) { | |
| cout << "Invalid operand: " << operand << endl; | |
| return; | |
| } | |
| cout << "Enter first number: "; | |
| cin >> num1; | |
| cout << "Enter second number: "; | |
| cin >> num2; | |
| } | |
| void calculate() | |
| { | |
| valid = true; // assume the operand is valid by default | |
| switch (operand) { | |
| case '+': | |
| result = num1 + num2; | |
| break; | |
| case '-': | |
| result = num1 - num2; | |
| break; | |
| case '/': | |
| result = num1 / num2; | |
| break; | |
| case '*': | |
| result = num1 * num2; | |
| break; | |
| case '%': | |
| result = (int)num1 % (int)num2; | |
| break; | |
| default: | |
| valid = false; // set the flag to false if the operand is invalid | |
| break; | |
| } | |
| } | |
| void printResults() | |
| { | |
| if (!valid) { // only print the results if the operand is valid | |
| cout << "Result: Use a supported operand (* / % + -) " << operand << " cannot be used." << endl; | |
| return; | |
| } | |
| cout << "Performing " << num1 << " " << operand << " " << num2 << endl; | |
| cout << "Result: " << result << endl; | |
| } | |
| } | |
| } | |
| int main(int argc, char const *argv[]) | |
| { | |
| // Call the functions from the nested namespace | |
| calculator::functions::getUserInput(); | |
| calculator::functions::calculate(); | |
| calculator::functions::printResults(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment