判断布尔表达式

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int   len =120; 
char infix[len],suffix[len];
void infixtosuffix()//将前缀表达式转换成后缀表达式 
{
	int top=-1,i=0,j=0;
	char ch=infix[0],stk[len];
	while(ch!='/0')
	{
		if(ch==' ')
		{}
		else if(ch=='(')
		{
			top++;stk[top]=ch;
		}
		else if(ch==')')
		{
			while(stk[top]!='(')
			{
				suffix[j++]=stk[top];top--;
			}
			top--;
		}
		else if(ch=='!')
		{
			top++;stk[top]=ch;
		}
		else if(ch=='&')
		{
			while(stk[top]=='&'||stk[top]=='!')
			{
				suffix[j++]=stk[top];top--;
			}
			top++;stk[top]=ch;
		}
		else if(ch=='|')
		{
			while(top!=-1&&stk[top]!='(')
			{
				suffix[j++]=stk[top];top--;
			}
			top++;stk[top]=ch;
		}
		else
		{
			suffix[j++]=ch;
			while(top!=-1&&stk[top]=='!')
			{
				suffix[j++]=stk[top];top--;
			}
		}
		ch=infix[++i];
	}
	while(top!=-1)
	{
		suffix[j++]=stk[top];top--;
	}
	suffix[j++]='/0';
}
void pri_result()//对后缀数组进行计算 
{
	int i=0,top=-1;
	char ch=suffix[i];
	bool result[len];
	while(ch!='/0')
	{
		if(ch=='F')
		{
			top++;result[top]=false;
		}
		else if(ch=='V')
		{
			top++;result[top]=true;
		}
		else if(ch=='!')
			result[top]=!result[top];
		else if(ch=='|')
		{
			result[top-1]|=result[top];
			top--;
		}
		else if(ch=='&')
		{
			result[top-1]&=result[top];
			top--;
		}
		ch=suffix[++i];
	}
	if(result[top]==true)
		printf("V/n");
	else printf("F/n");
}
int main()
{
	int i=1;
	while(cin.getline(infix,len))
	{
		infixtosuffix();
		printf("Expression %d: ",i++);
		pri_result();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值