前前后后改了好几次才终于过了,不过虽然过了,程序还有些冗杂,后续想想该怎么改。
后缀表达式,又称逆波兰式,指的是不包含括号,运算符放在两个运算对象的后面,所有的计算按运算符出现的顺序,严格从左向右进行。
运用后缀表达式进行计算的具体做法:
建立一个操作数栈S。然后从左到右读表达式,如果读到操作数就将它压入栈S中,如果读到n元运算符(即需要参数个数为n的运算符)则取出由栈顶向下的n项操作数进行运算,再将运算的结果代替原栈顶的n项压入栈中。重复上面过程,如果后缀表达式读完且栈中只剩一个操作数,则该数就是运算结果;如果后缀表达式读完但是栈中操作数多于一个,则后缀表达式错误;如果栈中操作数只剩一个,但是后缀表达式还未读完且当前运算符为双元操作符,则后缀表达式同样错误。
输入格式:
在一行中输入一个以#号结束的非空后缀式,#不属于表达式的一部分,操作数和运算符都以空格分隔,运算数为绝对值不超过100的整数,运算符仅有+、-、*、/ 四种。
输出格式:
输出后缀式计算结果,所有的计算都只取结果的整数部分。题目保证计算的中间和最后结果的绝对值都不超过109。
如果执行除法时出现分母为零的非法操作,则在一行中输出:Error: X/0,X是当时的分子。
如果后缀表达式中运算符多了或者少了,则在一行中输出:Expression Error: X,X是当时栈顶元素。
样例1">输入样例1:
5 -2 + 3 * #
输出样例1:
9
输入样例2:
5 -2 2 + / #
输出样例2:
Error: 5/0
输入样例3:
5 -1 3 + / - * #
代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct {
ElemType data[MAXSIZE];
int top;
}SqStack;
void InitStack(SqStack *S){
S->top = -1;
}
bool push(SqStack *S, ElemType e)
{
if(S->top == MAXSIZE-1)
{
return false;
}
S->top++;
S->data[S->top] = e;
return true;
}
bool pop(SqStack *S, ElemType *e)
{
if(S->top == -1)
{
return false;
}
*e = S->data[S->top];
S->top--;
return true;
}
int calculation(char *str)
{
int i = 0;
int flag=0,temp=0;
SqStack S;
InitStack(&S);
ElemType number_to_push, num1, num2;
while (str[i] != '#')
{
if (str[i] != ' ')
{
if (str[i] >= '0' && str[i] <= '9')
{
number_to_push = 0;
while (str[i] != ' ' && str[i])
{
number_to_push = number_to_push * 10 + (str[i] - '0');
i++;
}
push(&S, number_to_push);
flag++;
}
else if (str[i]=='-'&&str[i+1]!=' ')
{
number_to_push = 0;
i++;
while (str[i]!= ' ' && str[i])
{
number_to_push = number_to_push * 10 - (str[i] - '0');
i++;
}
push(&S, number_to_push);
flag++;
}
else
{
pop(&S, &num2);
pop(&S, &num1);
temp++;
if(temp<=flag-1)
{
switch (str[i])
{
case '+': {
num1 += num2;
break;
}
case '-': {
num1 -= num2;
break;
}
case '*': {
num1 *= num2;
break;
}
case '/': {
if (num2 == 0)
{
printf ("Error: %d/0",num1);
return false;
}
num1 /= num2;
break;
}
}
push(&S, num1);
}
else
{
printf ("Expression Error: %d",num1);
return false;
}
}
}
i++;
}
pop(&S, &num1);
if(S.top == -1)
{
printf ("%d",num1);
return true;
}
else
{
printf ("Expression Error: %d",num1);
}
}
int main()
{
char arr[50];
int j;
for(j=0;j<50;j++)
{
scanf("%c",&arr[j]);
if(arr[j]=='#')
break;
}
calculation(arr);
return 0;
}