#include<iostream>
using namespace std;
typedef int Status;
#define MAXSIZE 100
typedef char ElemType;
typedef struct
{
ElemType* base;
ElemType* top;
int stacksize;
}SqStack;
Status InitStack(SqStack& s)//初始化
{
s.base = new ElemType[MAXSIZE];
if (s.base == NULL)
return -1;
s.top = s.base;
s.stacksize = MAXSIZE;
return 0;
}
Status Push(SqStack& s, ElemType e)//入栈
{
if (s.top == s.stacksize + s.base)
return -1;
*s.top = e;
s.top++;
return 0;
}
Status Pop(SqStack& s, ElemType& e)//出栈
{
if (s.base == s.top)
return -1;
e = *(s.top - 1);
s.top--;
return 0;
}
ElemType GetTop(SqStack s)//取栈顶元素
{
if (s.top != s.base)
return *(s.top - 1);
}
Status In(ElemType ch)//判断是否为运算符
{
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '(' || ch == ')'||ch=='#')
return 1;
else
return 0;
}
Status Precede(ElemType a, ElemType b)//比较符号优先级
{
if (a == '#')
if (b == '#')
return '=';
else
return '<';
if (a == '+' || a == '-')
if (b == '*' || b == '/' || b == '(')
return '<';
else
return '>';
if (a == '*' || a == '/')
if (b == '(')
return '<';
else
return '>';
if (a == '(')
if (b == ')')
return '=';
else
return '<';
if (a == ')')
return '>';
}
Status Operate(ElemType a, ElemType ch, ElemType b)//进行二元运算
{
if (ch == '+')
return a + b;
if (ch == '-')
return a - b;
if (ch == '*')
return a * b;
if (ch == '/')
return a / b;
}
int EvaluateExpression()
{
SqStack OPND,OPTR;
char ch,m;
ElemType x, y;
InitStack(OPND);
InitStack(OPTR);
Push(OPTR,'#');
cin >> ch;
while (ch != '#' || GetTop(OPTR) != '#')
{
if (In(ch)==0)
{
Push(OPND, ch-'0');
cin >> ch;
}
else
switch (Precede(GetTop(OPTR), ch))
{
case '<':
{
Push(OPTR, ch);
cin >> ch;
break;
}
case '>':
{
Pop(OPTR, m);
Pop(OPND, y);
Pop(OPND, x);
Push(OPND, Operate(x, m, y));
break;
}
case '=':
{
Pop(OPTR, m);
cin >> ch;
break;
}
}
}
return GetTop(OPND);
}
int main()
{
cout << "输入表达式:" << endl;
cout << "计算结果为:" << EvaluateExpression();
}

数据结构表达式求值。为什么8*5*3算出来是120,而8*5*4却是-96,想问一下哪里有问题?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- CSDN专家-link 2021-10-16 17:02关注
因为数据类型都是char型,取值范围是-128到127,853=120在取值范围内,所以没问题;但854=160,超过127,溢出了,就成为负数了。负数值等于160-256=-96
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用