-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.cpp
63 lines (53 loc) · 1.6 KB
/
calculator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <stdexcept>
using namespace std;
// Function to perform calculations
double calculate(double num1, double num2, char operation) {
switch (operation) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
if (num2 != 0) {
return num1 / num2;
} else {
throw runtime_error("Error: Division by zero");
}
default:
throw invalid_argument("Error: Unsupported operation");
}
}
int main() {
cout << "Simple Calculator" << endl;
while (true) {
try {
double num1, num2;
char operation;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter operation (+, -, *, /): ";
cin >> operation;
cout << "Enter second number: ";
cin >> num2;
double result = calculate(num1, num2, operation);
cout << "Result: " << result << endl;
cout << "Do you want to perform another calculation? (yes/no): ";
string continueCalc;
cin >> continueCalc;
if (continueCalc != "yes") {
break;
}
} catch (const runtime_error& e) {
cout << e.what() << endl;
} catch (const invalid_argument& e) {
cout << e.what() << endl;
} catch (...) {
cout << "An unexpected error occurred." << endl;
}
}
cout << "Goodbye!" << endl;
return 0;
}