I'm working on a infix calculator for one of my classes and I'm fairly new to stacks and such and I have hit a wall when its comes to implementing the execution of the operations of the values. The function used for executing only receives a operator and one value parameter, so I'm lost as to how to perform the operations on a value when I need two. I am basing my code off of pseudo-code that was supplied by the professor (This is a picture of it). If anyone could point me in the right direction I'd appreciate it. This is what I have.
int main()
{
stack<char> op;
stack<int> val;
int result;
char ch;
cin >> ch;
while (ch != 'Q') //Once it reads 'Q' the program quits
{
switch (ch)
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
val.push(ch);
break;
case '(':
op.push(ch);
break;
case '+': case '-': case '*': case '/':
if (op.empty())
{
op.push(ch);
}
else if (Precedence(ch) > Precedence(op.top()))
{
op.push(ch);
}
else
{
while ( (!op.empty()) && (Precedence(ch) <= Precedence(op.top())) )
{
Execute(op, val);
}
op.push(ch);
}
break;
case ')':
{
while (op.top() != '(')
{
Execute(op, val);
}
op.pop();
break;
}
}
cin >> ch;
}
while (!op.empty())
{
Execute(op, val);
}
val.top(result);
return 0;
}
int Precedence(char oper)
{
if ( oper=='*' || oper=='/')
return 2;
else if( oper=='+' || oper=='-')
return 1;
else
return 0;
}
void Execute(stack<char>& op, stack<int>& val)
{
switch (op)
{
case '+':
result = val + val; //Unsure how to get results
break;
case '-':
result = val - val; //Unsure how to get results
break;
case '*':
result = val * val; //Unsure how to get results
break;
case '/':
result = val / val; //Unsure how to get results
break;
}
return result;
}
Aucun commentaire:
Enregistrer un commentaire