该程序适用于8 5 * =(输出40),但为更复杂的表达式(如8 4 5 - * = IT输出120)产生意外的结果,该程序正常工作,当时从堆栈操作中应为8 *(4-- 5)= -8。 first_op是第一个,第二_op是第二个操作数。
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define STACK_SIZE 99
int top = 0;
char stack[STACK_SIZE];
bool is_full();
bool is_empty();
void push(char);
char pull();
void stack_underflow();
void stack_overflow();
int main(void)
{
char first_op, sec_op, ch;
printf("Enter an RPN expression: ");
for(;;) {
scanf(" %c", &ch);
if (ch <= '9' && ch >= '0')
push(ch);
else if (ch != '=') {
sec_op = pull() - 48;
first_op = pull() - 48;
switch (ch) {
case '+': push(first_op + sec_op);
break;
case '-': push(first_op - sec_op);
break;
case '*': push(first_op * sec_op);
break;
case '/': push(first_op / sec_op);
}
}
if (ch == '=') {
printf("%d\n", stack[0]);
exit(EXIT_SUCCESS);
}
}
}
bool is_full(void)
{
return (top == STACK_SIZE);
}
bool is_empty(void)
{
return top == 0;
}
void push(char ch)
{
if (is_full())
stack_overflow();
else stack[top++] = ch;
}
char pull(void)
{
if (is_empty())
stack_underflow();
else return stack[--top];
}
void stack_overflow(void)
{
printf("Too complex expression\n");
exit(EXIT_FAILURE);
}
void stack_underflow(void)
{
printf("Not enough operands\n");
exit(EXIT_FAILURE);
}
您已经在错误的位置进行了ASCII调整,当您从堆栈中提取值时,因此,当您推动计算值时,稍后将不必要地调整它。
if (ch <= '9' && ch >= '0')
push(ch);
else if (ch != '=') {
sec_op = pull() - 48;
first_op = pull() - 48;
if (ch <= '9' && ch >= '0')
push(ch - '0');
else if (ch != '=') {
sec_op = pull();
first_op = pull();
您将获得预期的结果。请注意,我正在使用
'0'
48
。