-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprefix_calc.cpp
More file actions
42 lines (32 loc) · 996 Bytes
/
Copy pathprefix_calc.cpp
File metadata and controls
42 lines (32 loc) · 996 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
#include <iostream> // std::cin std::cout std::endl std::string
#include <string> // std::string std::stof
/* Polish notation:
* operators precede the numbers they act on.
* one benefit is there is no need for order of operations.
* The expression `* 2 + 1 3` is the same as `2 * (1 + 3)`
*/
// this gets a value/evaluates an operator
float procExpr() {
// this could be a number or an operator
std::string valOrOp;
std::cin >>valOrOp; // std::cin tokenizes the input for us
// addition
if (valOrOp == "+")
return procExpr() + procExpr(); // recursion
// subtraction
else if (valOrOp == "-")
return procExpr() - procExpr();
// multiplication
else if (valOrOp == "*")
return procExpr() * procExpr();
// division
else if (valOrOp == "/")
return procExpr() / procExpr();
else // it's a number (hopefully)
return std::stof(valOrOp); // convert input to a float
}
// calculator prompt
int main() {
while (true)
std::cout <<">" <<procExpr() <<std::endl;
}