-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathsimpleCalculator.cpp
More file actions
52 lines (41 loc) · 1007 Bytes
/
simpleCalculator.cpp
File metadata and controls
52 lines (41 loc) · 1007 Bytes
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
#include <iostream>
using namespace std;
// User-defined function
float calculate(float num1, float num2, char op)
{
switch (op)
{
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
if (num2 == 0)
{
cout << "Error! Division by zero.\n";
return 0;
}
return num1 / num2;
default:
cout << "Error! Operator is not correct.\n";
return 0;
}
}
int main()
{
char op;
float num1, num2, result;
cout << "Enter operator (+, -, *, /): ";
cin >> op;
cout << "Enter two operands: ";
cin >> num1 >> num2;
result = calculate(num1, num2, op);
// Print result only if operator is valid
if (op == '+' || op == '-' || op == '*' || op == '/')
{
cout << num1 << " " << op << " " << num2 << " = " << result;
}
return 0;
}