3rd Assignment
3rd Assignment
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
cout << "Simple Calculator Program\n";
cout << "-------------------------\n";
switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
cout << "Error: Division by zero is not allowed.\n";
return 1;
}
break;
default:
cout << "Error: Invalid operator. Please use +, -, *, or /.\n";
return 1;
}
cout << fixed << setprecision(2);
cout << "Result: " << num1 << " " << operation << " " << num2 << " = " << result << endl;
1. Input Handling:
The user is asked to provide two numbers and a mathematical operator (+, -, *, or /).
Inputs are read using cin.
2. Processing Logic:
A switch-case statement determines the operation to perform based on the operator:
Addition (+): Adds the two numbers.
Subtraction (-): Subtracts the second number from the first.
Multiplication (*): Multiplies the two numbers.
Division (/): Divides the first number by the second, with a check to ensure the divisor is
not zero.
Invalid operators trigger an error message, and the program exits gracefully.
3. Output Formatting:
The <iomanip> library is used to format the result to two decimal places using fixed and
setprecision(2). This ensures the output is user-friendly and consistent.
4. Error Handling:
Division by zero is explicitly handled with an error message.
Invalid operators are caught, and the program exits with a message indicating the error.
5. Decisions Made:
Use of switch-case:
Chosen for clarity and readability, allowing straightforward addition of new operations if
needed.
Formatting:
The result is displayed with two decimal places to ensure a professional and clean output
format.
Error Handling:
Ensures the program handles common user mistakes (e.g., division by zero, invalid
operator) gracefully without crashing.
6. Example Outputs:
Valid Input:
Input: 5, *, 3
Output: Result: 5.00 * 3.00 = 15.00
7. Division by Zero:
Input: 10, /, 0
Output: Error: Division by zero is not allowed.
8. Invalid Operator:
Input: 4, x, 2
Output: Error: Invalid operator. Please use +, -, *, or /.