how do I evaluate rpn?

as the title says, what is a way to evaluate rpn- eg this statement(5, 5, 54, /, +,) how would I evaluate it into an answer? no need figured it out
Last edited on
Lots written about that on internet.

Show some code.
Well first decide on the method - shunting yard, RDP (recursive descent parser) etc.
@seeplus i already did, i got the statement into rpn
I got the statement into RPN
The hard part is behind you.

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
#include <iostream>

struct token
{ 
  union { double x; char o; };
  bool is_number;   
  token(double x): x(x), is_number(true) {}
  token(char o): o(o), is_number(false) {} 
};

int main()
{    
  token expr[] = { 4.0, 3.0, 2.0, '+', '*', 3.0, 1.5, '/', '/', 0.1, '+' };
    
  token const* const begin = expr;
  token const* const end = expr + (sizeof(expr) / sizeof(*expr)); 
  token* next = expr;
  token* top  = expr;
    
  struct underflow_exception {}; 
  auto const pop_operand = [&]{ return top == begin? throw underflow_exception{}: (--top)->x; }; 
    
  for ( ;; ++next, ++top )
  {
    while (next != end && next->is_number) *top++ = *next++; 
    if (next == end) break;
  
    double const op2 = pop_operand();
    double const op1 = pop_operand();

    if (next->o == '/') *top = op1 / op2;
    if (next->o == '+') *top = op1 + op2;
    if (next->o == '-') *top = op1 - op2;
    if (next->o == '*') *top = op1 * op2;
  }
    
  std::cout << std::fixed << pop_operand() << '\n';
}
Last edited on
oh @mbozzi, i h already did it, i was just replying to the guy after I finished it but thanks
Last edited on
Topic archived. No new replies allowed.