您的位置:首页 > 其它

布尔表达式判别程序

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐