资源预览内容
第1页 / 共3页
第2页 / 共3页
第3页 / 共3页
亲,该文档总共3页全部预览完了,如果喜欢就下载吧!
资源描述
#include#include/包含函数isdigit原型#includestack.h/链栈类模板#includemathoperator.h/配有运算符类int isoperator(char ch)/判断运算符和左括号return(ch=+|ch=-|ch=*|ch=/|ch=();int iswhitespace(char ch)/判断空格符,格式符和换行符return(ch=32|ch=t|ch=n);/32是空格符代码void Error(char *c)cerrcendl;exit(1);/从操作数栈Opnds取出两个数,进行运算符optr指定的计算,然后将结果压回操作数栈void Evaluate(Stack& OpndS,MathOperator optr)double opnd1=OpndS.Pop();double opnd2=OpndS.Pop();switch(optr.op)case+: OpndS.Push(opnd2+opnd1);break;case-: OpndS.Push(opnd2-opnd1);break;case*: OpndS.Push(opnd2*opnd1);break;case/: OpndS.Push(opnd2/opnd1);break;int main()int rank=0;char ch;double number;MathOperator optr1,optr2;Stack opndS; /操作数栈Stack optrS; /运算符栈coutEnter an infix:number;/从输入缓冲区读取一个完整的操作数rank+;if(rank1)Error(Operator expected);opndS.Push(number);else if(isoperator(ch) /读入运算符,包括左括号if(ch!=()/读入运算符,且非左括号rank-;if(rank=optr1)optr2=optrS.Pop();Evaluate(opndS,optr2);optrS.Push(optr1); else if(ch=)/读入右括号optr1=MathOperator(ch);while(!optrS.Empty()&optrS.Top()=optr1)/取出子表达式运算符optr2=optrS.Pop();Evaluate(opndS,optr2);if(optrS.Empty()/没有遇到左括号Error(Missing left parenthesis);optrS.Pop(); /删除左括号else if(!iswhitespace(ch)/读取空格或换行符,继续读取。Error(Invalid input);if(rank!=1)/读入结束符,rank必须为1,否则输入非法Error(Operand expected);while(!optrS.Empty()/清空运算符栈optr2=optrS.Pop();if(optr2.op=()Error(Missing right parenthesis);Evaluate(opndS,optr2);coutThe value is opndS.Pop()endl;/显示结果return(0);
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号