这里只能用于计算十以内的表达式
/**
*
* 作者: LinX 2017-6-18 - 2017-6-19
*
*
* 内容: 运用栈对中缀表达式求值
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100
char oper[MAXSIZE]; //操作符栈
int topOper=-1; //栈顶指针
int nums[MAXSIZE]; //数字栈
int topNums=-1; //栈顶指针
int MedExp(char *exp,int *res); //计算表达式值
int countStackTopTwo(); //计算两个栈顶元素相加
int count(char op,int num1,int num2,int *result); //计算每一步两个数相加
int judgePrior(char op); //比较符号的优先级
int main()
{
int res;
char exp[MAXSIZE];
printf("输入表达式: ");
gets(exp);
if(MedExp(exp,&res)==0)
{
printf("表达式错误!\n");
return 0;
}
printf("%d\n",res);
return 0;
}
int countStackTopTwo()
{
int result;
char op=oper[topOper--];
int num1=nums[topNums--];
int num2=nums[topNums--];
if(count(op,num2,num1,&result)==0)
{
//printf();
return 0;
}
nums[++topNums]=result;
//printf("res=%d\n",result);
return 1;
}
int MedExp(char *exp,int *res)
{
int i=0,flag,j=0;
while(exp[i]!='\0')
{
if('0'<=exp[i]&&exp[i]<='9')
{
nums[++topNums]=exp[i]-'0';
}
else if(exp[i]=='(')
{
oper[++topOper]=exp[i];
}
else if(topOper==-1)
{
oper[++topOper]=exp[i];
}
else if(exp[i]=='+'||
exp[i]=='-'||
exp[i]=='*'||
exp[i]=='/')
{
if(oper[topOper]=='('||judgePrior(exp[i])>judgePrior(oper[topOper]))
{
oper[++topOper]=exp[i];
}
else
{
flag=countStackTopTwo();
if(flag==0)
{
return 0;
}
oper[++topOper]=exp[i];
}
}
else if(exp[i]==')')
{
while(oper[topOper]!='(')
{
flag=countStackTopTwo();
if(flag==0)
{
return 0;
}
}
topOper--;
}
i++;
}
while(topOper!=-1)
{
flag=countStackTopTwo();
if(flag==0)
{
return 0;
}
}
*res=nums[topNums];
return 1;
}
int count(char op,int num1,int num2,int *result)
{
if(op=='+')
{
*result=num1+num2;
}
else if(op=='-')
{
*result=num1-num2;
}
else if(op=='*')
{
*result=num1*num2;
}
else if(op=='/')
{
if(num2==0)
{
return 0;
}
*result=num1/num2;
}
return 1;
}
int judgePrior(char op)
{
if(op=='+'||op=='-')
{
return 0;
}
return 1;
}