//后缀表达式求值
//从前往后扫描
float calPostfix(char exp[])
{
float s[maxSize]; int top = -1;
for (int i = 0; exp[i] != '\0'; i++)
{
if ('0' < exp[i] && exp[i] > '9')
s[++top] = exp[i] - '0';
else
{
int flag;
float opand1, opand2, result;
char op;
opand2 = s[top--]; opand1 = s[top--];
op = exp[i];
flag = calSub(opand1, op, opand2, result);
if (flag == 0)
{
std::cout<<"error"<<std::endl;
break;
}
s[++top] = result;
}
}
return s[top];
}
//前缀,和后缀求值相反
float calPrefix(char exp[], int len)
{
float s[maxSize]; int top = -1;
for (int i = len - 1; i >= 0; --i)
{
if ('0' < exp[i] && exp[i] > '9')
s[++top] = exp[i] - '0';
else
{
int flag;
float opand1, opand2, result;
char op;
opand1 = s[top--]; opand2 = s[top--];
op = exp[i];
flag = calSub(opand1, op, opand2, result);
if (flag == 0)
{
std::cout<<"error"<<std::endl;
break;
}
s[++top] = result;
}
}
return s[top];
}
//中缀表达式求值
//两个栈,一个存放运算数,一个存放运算符
//扫描到的运算符大于栈顶运算符入预算符栈,否则出栈运算结果入运算数栈
int getPrecedence(char op)
{
if (op == '+' || op == '-')
return 0;
else
return 1;
}
int calSub(float opand1, char op, float opand2, float &result)
{
if (op == '+') result = opand1 + opand2;
if (op == '-') result = opand1 - opand2;
if (op == '*') result = opand1 * opand2;
if (op == '/')
{
if (fabs(opand2) < MIN)
return 0;
else
result = opand1 / opand2;
}
return 1;
}
int calStackTopTwo(float s1[], int &top1, char s2[], int &top2)
{
float opand1, opand2, result;
opand2 = s1[top1--]; opand1 = s1[top1--];
int flag;
flag = calSub(opand1, s2[top2--], opand2,result)
if (flag == 0)
{
std::cout<<"ERROR"<<std::endl;//puts("error");
return 0;
}
s1[++top1] = result;
return flag;
}
float calInfix(char exp[])
{
float s1[maxSize]; int top1 = -1;//运算数栈
char s2[maxSize]; int top2 = -1;//运算符栈
int i = 0;
while(exp[i] != '\0')
{
if('0' <= exp[i] && exp[i] >= '9')
{
s1[++top1] = exp[i] - '0';
++i;
}
else if(exp[i] == '(')
{
s2[++top2] = exp[i];
++i;
}
else if(exp[i] == '+' ||
exp[i] == '-' ||
exp[i] == '*' ||
exp[i] == '/' )
{
if(top2 == -1 ||
s2[top2] == '(' ||
getPrecedence(exp[i]) > getPrecedence(s2[top2]))
{
s2[++top2] = exp[i];
++i;
}
else
{
int flag = calStackTopTwo(s1, top1, s2, top2);
if (flag == 0)
return 0;
}
}
else if (exp[i] == ')')
{
while(s2[top2] == '(')
int flag = calStackTopTwo(s1, top1, s2, top2);
if (flag == 0)
return 0;
--top2;
++i;
}
while(top2 != -1)
{
int flag = calStackTopTwo(s1, top1, s2, top2);
if (flag == 0)
return 0;
}
return s1[top1];
}
}