编写一个简单程序C语言计算后缀表达式的值
时间: 2023-05-28 17:07:22 浏览: 123
C语言 后缀表达式计算.doc
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 50
typedef struct{
int data[MAX];
int top;
}Stack;
void InitStack(Stack *s){
s->top=-1;
}
int IsEmpty(Stack *s){
if(s->top==-1){
return 1;
}
return 0;
}
int IsFull(Stack *s){
if(s->top==MAX-1){
return 1;
}
return 0;
}
int Push(Stack *s,int x){
if(IsFull(s)){
return 0;
}
s->top++;
s->data[s->top]=x;
return 1;
}
int Pop(Stack *s,int *x){
if(IsEmpty(s)){
return 0;
}
*x=s->data[s->top];
s->top--;
return 1;
}
int GetTop(Stack *s,int *x){
if(IsEmpty(s)){
return 0;
}
*x=s->data[s->top];
return 1;
}
int main(){
Stack s;
InitStack(&s);
char exp[MAX];
int i,len,a,b,c;
printf("请输入后缀表达式:");
gets(exp);
len=strlen(exp);
for(i=0;i<len;i++){
if(exp[i]>='0'&&exp[i]<='9'){
Push(&s,exp[i]-'0');
}else{
Pop(&s,&b);
Pop(&s,&a);
switch(exp[i]){
case '+':c=a+b;break;
case '-':c=a-b;break;
case '*':c=a*b;break;
case '/':c=a/b;break;
}
Push(&s,c);
}
}
Pop(&s,&c);
printf("后缀表达式的值为:%d\n",c);
return 0;
}
阅读全文