C程序代码-中缀表达式求值

上传人:鲁** 文档编号:479392565 上传时间:2024-02-01 格式:DOC 页数:3 大小:15.51KB
返回 下载 相关 举报
C程序代码-中缀表达式求值_第1页
第1页 / 共3页
C程序代码-中缀表达式求值_第2页
第2页 / 共3页
C程序代码-中缀表达式求值_第3页
第3页 / 共3页
亲,该文档总共3页,全部预览完了,如果喜欢就下载吧!
资源描述

《C程序代码-中缀表达式求值》由会员分享,可在线阅读,更多相关《C程序代码-中缀表达式求值(3页珍藏版)》请在金锄头文库上搜索。

1、#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指定的计算,然后将结果压回操作数栈vo

2、id 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;M

3、athOperator 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); els

4、e 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);

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 文学/艺术/历史 > 人文/社科

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号