数据结构实验之栈与队列三:后缀式求值
Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
Output
求该后缀式所对应的算术表达式的值,并输出之。
Sample
Input
59684/-3+#
Output
57
Hint
基本操作数都是一位正整数!
#include <stdio.h>
#include <stdlib.h>
int main()
{
int top, b[110];
char a;
top = 0;
while (scanf("%c", &a) && a != '#')
{
if (a >= '0' && a <= '9')
{
b[++top] = a - '0';
/*字符0~9通过减去字符'0'可以获得数值,原理是ASCII码中,字符0~9对应的ASCII值与字符'0'的差值即为数值。如:字符‘9’的ASCII码值是57,
字符‘0’的ASCII码值是48,‘9’-‘0’可等价转换成 57 - 48 = 9,所以可用以下方式进行转换。*/
}
else if (a == '+')
{
b[top - 1] = b[top - 1] + b[top];
top--;
}
else if (a == '-')
{
b[top - 1] = b[top - 1] - b[top];
top--;
}
else if (a == '*')
{
b[top - 1] = b[top - 1] * b[top];
top--;
}
else if (a == '/')
{
b[top - 1] = b[top - 1] / b[top];
top--;
}
}
printf("%d", b[top]);
}
可能大家在对后缀式的计算不太了解,这里有一篇可以帮助大家理解后缀式计算的博客→图解后缀表达式的计算过程