布尔表达式判别程序
2010-11-02 18:46
190 查看
程序很简单,用栈实现,把中缀表达式转换成后缀表达式是关键,从下午2点调试到晚上6点,中间洗了一次澡,发现VS2010的调试功能很强大,一开始用标准库的Stack,发现在判别的时候会出现问题,具体是在栈空的时候,调用s.top()会出现错误,所以通过一个字符数组和一个整数来自己模仿指针的话这个错误就会避免 。下面是源代码。
// ajax.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<iostream> #include<vector> #include<cmath> #include<string> #include<fstream> #include<stack> using namespace std; const int MAX_STRLEN=256; const int MAX_STACKSIZE=256; void InfixToSuffix(const char* infix,char *suffix); bool Compute(const char*suffix); int _tmain(int argc, _TCHAR* argv[]) { ifstream cin("d://1.txt"); char infix[MAX_STRLEN], suffix[MAX_STRLEN]; int t=0; while(cin.getline(infix,MAX_STRLEN)) { t++; InfixToSuffix(infix,suffix); bool res=Compute(suffix); cout<<"Expression"<<t<<":"; if(res) cout<<"True"<<endl; else cout<<"False"<<endl; } system("pause"); return 0; } void InfixToSuffix(const char* infix,char *suffix) { int top; char stk[MAX_STACKSIZE]; int i=0, j=0; top=-1; char ch=infix[i]; while(ch!='/0') { if(ch==' ') {} else if(ch=='(') {top++;stk[top]=ch;} //字符"("入栈 else if(ch==')') { while(stk[top]!='(') //将栈顶到字符"("之间的运算符依次出栈并且插入suffix尾部 { suffix[j]=stk[top]; top--; j++; } top--; //字符"("出栈 } else if(ch=='|') { while(top!=-1&&stk[top]!='(') //将优先级不小于运算符"|"的所有运算符依次出栈并输入suffix尾部 { suffix[j]=stk[top]; top--; j++; } top++;//"|"入栈 stk[top]=ch; } else if(ch=='&') { while(stk[top]=='&'||stk[top]=='!') //将运算符不小于"&"的所有运算符依次出栈并输入suffix尾部 { suffix[j]=stk[top]; top--; j++; } top++; //"&"入栈 stk[top]=ch; } else if(ch=='!') //'!'入栈 { top++; stk[top]=ch; } else { suffix[j]=ch;// 将ch输入suffix尾部 j++; while(top!=-1&&stk[top]=='!') //将所有运算符'!'依次出栈并输入suffix尾部 { suffix[j]=stk[top]; top--; j++; } } i++; ch=infix[i]; } while(top!=-1) { suffix[j]=stk[top]; top--; j++; } suffix[j]='/0'; } bool Compute(const char* suffix) { stack<bool> s; int i=0; char ch=suffix[i]; while(ch!='/0') { if(ch=='|') { bool op1=s.top(); s.pop(); bool op2=s.top(); op2|=op1; s.top()=op2; } else if(ch=='&') { bool op1=s.top(); s.pop(); bool op2=s.top(); op2&=op1; s.top()=op2; } else if(ch=='!') { s.top()=!s.top(); } else if(ch=='V') s.push(true); else if(ch=='F') s.push(false); i++; ch=suffix[i]; } return s.top(); }
相关文章推荐
- 正则表达式介绍,附程序开发常用正则表达式一览表
- 用栈来是实现表达式求解的小程序
- JavaScript程序开发(十四)—函数声明与函数表达式
- Kotlin——程序的灵魂组成之Lambda表达式、匿名函数、高阶函数的基本语法(二)
- 9.11 给定一个布尔表达式,由0、1、&、|、^等符号组成,以及一个想要的布尔结果result,实现一个函数,算出有几种括号的放法可使该表达式得出result的值。
- 按照规定,在高速公路上行使的机动车,超出本车道限速的10%则处200元罚款;若超出50%,就要吊销驾驶证。请编写程序根据车速和限速自动判别对该机动车的处理。
- (174)实用程序表达式
- [Java] 正则表达式 02 EmailSpider 抓邮件, CodeCounter 统计程序有效代码行数
- 【个人项目总结】C#四则运算表达式生成程序
- 正则表达式的验证程序
- 编写高质量代码改善C#程序的157个建议——建议37:使用Lambda表达式代替方法和匿名方法
- 每天一个小程序—0013题(爬图片+正则表达式 or BeautifulSoup)
- 判断程序是横屏竖屏的表达式
- Java正则表达式学习笔记,分离网页邮件地址的蜘蛛程序
- 在MFC程序中,利用boost 正则表达式获取URL参数示例
- * java程序性能优化 Posted on 2010-07-28 16:04 chinaifne 阅读(2246) 评论(0) 编辑 收藏 一、避免在循环条件中使用复杂表达式
- jsva程序:正则表达式匹配域名
- 运算符,语句和表达式有关的程序
- javascript 正则表达式测试小程序
- 正则表达式测试程序