怎么不过呀?
查看原帖
怎么不过呀?
481471
Eric12楼主2023/10/4 15:56

求助大佬,好久都没有发现问题。我是用中缀表达式转后缀表达式,再用后缀表达式求值做的。结果算的对,但是短路数量算的不对,怎么改啊?

另外,结构体里的duanlu是指这个数是不是由短路运算得到的

#include <cstdio>
#include <iostream>
#include <stack>
#include <string>
using namespace std;
struct num{
	char data;
	bool duanlu;
}; 
int getPriority(char op)
{
	switch(op)
	{
		case '(':return 0;
		case '&':return 2;
		case '|':return 1;
	}
}
int main()
{
	char ch;
	int cnta=0,cntb=0;
	string bds="";
	stack<char> s;
	stack<num> s1;
	while((ch=getchar())!=EOF)
	{
		if(ch=='(')
			s.push('(');
		else if (ch=='0'||ch=='1')
			bds+=ch;
		else if (ch=='&'||ch=='|')
		{
			while(s.size()&&getPriority(ch)<=getPriority(s.top()))
			{
				bds+=s.top();
				s.pop();
			}
			s.push(ch);
		}
		else if(ch==')')
		{
			while(s.top()!='(')
			{
				bds+=s.top();
				s.pop();
			}
			s.pop();
		}
	}
	while(s.size())
	{
		bds+=s.top();
		s.pop();
	}
	for(int i=0;i<bds.size();i++)
	{
		if(bds[i]=='0'||bds[i]=='1')
			s1.push(num({bds[i],false}));
		else if(bds[i]=='&')
		{
			num b=s1.top();s1.pop();			
			num a=s1.top();s1.pop();
			if(a.data=='0'&&!b.duanlu)
				cnta++;
			if(a.data=='0'||(a.duanlu||b.duanlu))
				s1.push(num{((a.data-'0')&(b.data-'0'))+'0',true});
			else s1.push(num{((a.data-'0')&(b.data-'0'))+'0',false});
		}
		else if(bds[i]=='|')
		{
			num b=s1.top();s1.pop();
			num a=s1.top();s1.pop();
			if(a.data=='1'&&!b.duanlu)
				cntb++;
			if(a.data=='1'||(a.duanlu||b.duanlu))
				s1.push(num{((a.data-'0')|(b.data-'0'))+'0',true});
			else s1.push(num{((a.data-'0')|(b.data-'0'))+'0',false});
		}
	}
	cout<<bds<<' '<<s1.top().data<<endl<<cnta<<' '<<cntb<<endl;
	return 0;
}
2023/10/4 15:56
加载中...