表达式求值

实验内容:

1、定义顺序栈;

2、用顺序栈实现表达式求值;

实验基本要求

掌握栈的特性和栈结构的入栈和出栈等操作,掌握栈在表达式求值中的应用

 

#include<iostream>
#include<stdio.h>
using namespace std;
#define MaxSize 50
#define MaxOp 7

struct{
 char ch;
 int pri;
}lpri[]={{'=',0},{'(',1},{'*',5},{'/',5},{'+',3},{'-',3},{')',6}},
 rpri[]={{'=',0},{'(',6},{'*',4},{'/',4},{'+',2},{'-',2},{')',1}};

int leftpri(char op){
 int i;
 for(i=0;i<MaxOp;i++)
  if(lpri[i].ch==op)return lpri[i].pri;
}

int rightpri(char op){
 int i;
 for(i=0;i<MaxOp;i++)
  if(rpri[i].ch==op)
   return rpri[i].pri;
}

bool InOp(char ch){
 if(ch=='('||ch==')'||ch=='+'||ch=='-'||ch=='*'||ch=='/')return true;
 else return false;
}

int Precede(char op1,char op2){
 if(leftpri(op1)==rightpri(op2))return 0;
 else if(leftpri(op1)<rightpri(op2))return -1;
 else return 1;
}

void trans(char *exp,char postexp[]){
 struct{
  char data[MaxSize];
  int top;
 }op;
 int i=0;
 op.top=-1;
 op.top++;
 op.data[op.top]='=';
 while(*exp!='\0'){
  if(!InOp(*exp)){
   while(*exp>='0'&&*exp<='9'){
    postexp[i++]=*exp;
    exp++;
   }
   postexp[i++]='#';
  }
  else{
   switch(Precede(op.data[op.top],*exp)){
   case -1:
    op.top++;op.data[op.top]=*exp;
    exp++;
    break;
   case 0:
    op.top--;
    exp++;
    break;
   case 1:
    postexp[i++]=op.data[op.top];
    op.top--;
    break;
   }
  }
 }
 while(op.data[op.top]!='='){
  postexp[i++]=op.data[op.top];
  op.top--;
 }
 postexp[i]='\0';
}

float compvalue(char *postexp){
 struct{
  float data[MaxSize];
  int top;
 }st;
 float d,a,b,c;
 st.top=-1;
 while(*postexp!='\0'){
  switch(*postexp){
  case '+':
   a=st.data[st.top];
   st.top--;
   b=st.data[st.top];
   st.top--;
   c=a+b;
   st.top++;
   st.data[st.top]=c;
   break;
  case '-':
   a=st.data[st.top];
   st.top--;
   b=st.data[st.top];
   st.top--;
   c=b-a;
   st.top++;
   st.data[st.top]=c;
   break;
  case '*':
   a=st.data[st.top];
   st.top--;
   b=st.data[st.top];
   st.top--;
   c=a*b;
   st.top++;
   st.data[st.top]=c;
   break;
  case '/':
   a=st.data[st.top];
   st.top--;
   b=st.data[st.top];
   st.top--;
   if(a!=0){
    c=b/a;
    st.top++;
    st.data[st.top]=c;
   }
   else{
    printf("\n\t除零错误!\n");
    exit(0);
   }
   break;
  default:
   d=0;
   while(*postexp>='0'&&*postexp<='9'){
    d=10*d+*postexp-'0';
    postexp++;
   }
   st.top++;
   st.data[st.top]=d;
   break;
  }
  postexp++;
 }
 return(st.data[st.top]);
}

int main(){
 char exp[]="(56*20)/(4-2)";
 char postexp[MaxSize];
 trans(exp,postexp);
 printf("中缀表达式:%s\n",exp);
 printf("后缀表达式:%s\n",postexp);
 printf("表达式的值:%g\n",compvalue(postexp));
 return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值