#include<stdio.h>
#include<stdlib.h>
#define max 50
//定义栈的大小
struct stack1
{
int data[max];
int top;
};
typedef struct stack1 Stack;
//建立链栈的结构体
Stack* initStack()
{
Stack*S=(Stack*)malloc(sizeof(Stack));
S->top=-1;
return S;
}
//把栈初始化
bool push(Stack*S,int x){
if(S->top==max-1)
return false;
//判断栈是否为满
else
{S->top++;
S->data[S->top]=x;
return true;
}
}
//压栈操作
int pop(Stack*S){
int x=S->data[S->top];
S->top--;
return x;
}
//出栈操作
int priority(char op){
switch(op){
case '+':
case '-':
return 1;
//加减的优先级为1;
case '*':
case '/':
return 2;
//乘除的优先级为2;
default:
return -1;
//其余的为-1;
}
}
//确定运算符的优先级
void poppush(Stack*OP,Stack*NUM){
char op;
int n1,n2,n;
op=pop(OP);//输出运算符
n1=pop(NUM);//输出栈顶的数
n2=pop(NUM);//输出栈顶的数
switch(op){
case '+':
n=n1+n2;
break;
case '-':
n=n1-n2;
break;
case '*':
n=n1*n2;
break;
case '/':
n=n1/n2;
break;
//加减运算
}
push(NUM,n);
//对运算结果压栈
}
int expvalve(char*s){
Stack*NUM=initStack();
Stack*OP=initStack();
//建立两个栈,一个存放运算符,一个存放数字;
while(*s!='\0'){
if(*s>='0'&&*s<='9')//计算的数在1到9之间
{
int x=*s-'0';
s++;
while(*s>='0'&&*s<='9')//计算两位数
{
x=x*10+(*s-'0');
s++;
}
push(NUM,x);
}
else if(OP->top==-1||*s=='('||priority(OP->data[OP->top])<priority(*s))
//运算符的优先级等于-1或指针s指向‘(’或 后一个运算符的优先级小于指针指向的
//对运算符的判断 ,优先级大于栈内的,压栈
{
push(OP,*s);
s++;
}
else if(*s==')'&&OP->data[OP->top]=='(')
{
pop(OP);
}
//有括号的运算,优先级小于栈内的出栈
else
poppush(OP,NUM);
}
while(OP->top>=0)
//表达式为空,依次输出运算符,输出一个运算符,输出两个数进行运算,直至空栈
poppush(OP,NUM);
int n=NUM->data[NUM->top];
free(OP);
free(NUM);
return n;
}
int main(){
char exp[max];
//建立的数组,存放表达式
printf("\n请输入表达式:");
gets(exp);//gets等价于scanf
printf("\n %s=%d\n\n",exp,expvalve(exp));
}
这是编写的代码但有的结果计算错误,为什么