【数据结构实验】实验四 算术表达式求值(必做,设计性实验,2学时)

来源:互联网 发布:全球经济指标数据网 编辑:程序博客网 时间:2024/05/21 10:39

代码部分参考《数据结构》的思路


编译环境:Microsoft Visual Studio 2010

经过本人测试,可正常运行并达到要求

ps:程序后来在2015打开时自动升级,由于兼容性问题导致达不到预期效果,所以请大家使用2010进行检测


// 实验四.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <stdio.h>#include <iostream>#include <malloc.h>#include <Windows.h>#include <string.h>#define STACK_INIT_SIZE 100;#define STACKINCREMENT 10;typedef char SElemType;char TableOPTR[]={'+','-','*','/','(',')','#'};    //大于为1,小于为2,等于为3,无法比较为0int TableOPTR_Log[7][7]={{1,1,2,2,2,1,1},{1,1,2,2,2,1,1},{1,1,1,1,2,1,1},{1,1,1,1,2,1,1},{2,2,2,2,2,3,0},{1,1,1,1,0,1,1},{2,2,2,2,2,0,3}};// A*3 B+1typedef struct SqStack{SElemType *base;SElemType *top;int stacksize;};int In(char c){   //判断是否为运算符char Table[]={'(',')','*','/','+','-','#'};int i;for(i=0;i<strlen(Table);i++){if(Table[i]==c) return 1;}return 0;}SElemType Precede(SElemType a, SElemType b)   //如果a<b则返回<,否则为>{int LA,LB;for(LA=0;LA<7;LA++){if(a==TableOPTR[LA]) break;}for(LB=0;LB<7;LB++){if(b==TableOPTR[LB]) break;}switch(TableOPTR_Log[LA][LB])//大于为1,小于为2,等于为3,无法比较为0{case 1:return '>';break;case 2:return '<';break;case 3:return '=';break;case 0:return '!';break;}}int InitStack(SqStack &S){   //初始化S.base=(SElemType *)malloc(100 * sizeof(SElemType));if(!S.base) exit(-100);S.top=S.base;S.stacksize=100;return 1;}char GetTop(SqStack S, SElemType &e){SElemType temp;if(S.top==S.base) return -10;e=*(S.top-1);return e;}char GetTop(SqStack S){SElemType temp;if(S.top==S.base) return -10;return *(S.top-1);}int Push(SqStack &S, SElemType e){if(S.top-S.base>=S.stacksize){  //栈满,追加存储空间S.base=(SElemType *)realloc(S.base,(S.stacksize+10)*sizeof(SElemType));if(!S.base) exit(-100);S.top=S.base +S.stacksize;    //由于重新分配了空间,需要对TOP进行重新指向S.stacksize+=10;}*S.top++=e;return 1;}SElemType Pop(SqStack &S, SElemType &e){if(S.top==S.base) return -10;e=*--S.top;return e;}//优先级顺序为(=) )>)SElemType Operate(SElemType a,SElemType theta, SElemType b){a-=48;b-=48;int c;printf("在最后操作函数中,a=%d,b=%d\n",a,b);switch(theta){case '+':printf("->  +");return a+b;break;case '-':printf("->  -");c=a-b;return c;break;case '*':printf("->  *");return a*b;break;case '/':printf("->  /");return a/b;break;default:return -1;break;}}char EvaluateExpression(){char c;int temp;SqStack OPTR,OPND;SElemType theta,x,a,b;InitStack(OPTR);InitStack(OPND);Push(OPTR,'#');c=getchar();while(c!='#' || GetTop(OPTR)!='#'){if(!In(c)) {Push(OPND,c);c=getchar();printf("IN A OPND\n");}else{switch(Precede(GetTop(OPTR),c)){case '<':Push(OPTR,c);c=getchar();break;case '=':Pop(OPTR,x);c=getchar();break;case '>':Pop(OPTR,theta);Pop(OPND,b);Pop(OPND,a);printf("a=%d  theta=%c  b=%d\n",a,theta,b);Push(OPND,Operate(a,theta,b)+48);printf("  =%d\n",Operate(a,theta,b));break;}}}return GetTop(OPND)-48;}int _tmain(int argc, _TCHAR* argv[]){printf("!!!!!!\n");printf("\n结果为:%d\n",EvaluateExpression());system("pause");return 0;}


阅读全文
0 0
原创粉丝点击