Frage

I have a program that is supposed to convert an expression into reverse polish notation, and then display the answer after performing the calculations. Right now it doesn't perform calculations correctly. For example, if I enter 5+2+5, it only registers the 5+2 for some reason. Can anyone tell me what I did wrong?

#include <iostream>
#include <stack>


void calculation(int, int, char);
using namespace std;
stack<int> a;

void main(void)
{

bool expression = false;
char ch;
char done;

int op1, op2;

cout << "Reverse Polish Notation : " << endl;
cout << "Enter expression: " << endl;
while (!expression)
{
    cin >> op1;
    cin >> op2;
    cin >> ch;

    calculation(op1, op2, ch);
    if (!cin)
        expression = false;
    else
    {
        expression = true;
        calculation(op1, op2, ch);
    }
}
cout << "Your expression is " <<  a.top() << endl;

}

void calculation(int oper1, int oper2, char chr)
{
switch (chr)
{
    case '+':
        a.push(oper1 + oper2);
        break;
    case '-':
        a.push(oper1 - oper2);
        break;
    case '*':
        a.push(oper1 * oper2);
        break;
    case '/':
        a.push(oper1 / oper2);
        break;

}
}
War es hilfreich?

Lösung

Your program does not convert anything. It is a very simple RPN calculator that takes a single term consisting of two operands and a binary operation and calculate the results.

If you need it to take more complex RPN inputs, you need to re-design the input and calculation logic.

If you want to input infix expressions like 5+4 but keep the internal representation as an RPN-stack, you will also have to write a parser which does that.

Andere Tipps

All operations should be to and from the stack. Your main loop should look more like

while not eol
   if reading an operator
       push result of applying operator to top two stack elements
   else if reading an integer
       read it and push it on to the stack
   else 
       print an error message

print value at top of stack

I omitted a pile of stack depth checks.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top