#1#4#5错误,求调
查看原帖
#1#4#5错误,求调
1007041
zhaozichu楼主2024/7/14 15:53
#include<bits/stdc++.h>
using namespace std;
string a,b;
int f[150],v[35],flag;
stack<char>s; 
stack<int>s2;
stack<int>s3;
int main()
{
	cin>>a;
	f['+']=4,f['-']=4,f['*']=3,f['/']=3,f['^']=2,f['(']=5,f[')']=1;
	for(int i=0;i<a.size();i++)
	{
		if(a[i]=='-')
		{
			if(i==0)
			{
				a.erase(i,1);
				v[i]=1;
				i--;
			}
			else if(a[i-1]=='+'||a[i-1]=='-'||a[i-1]=='*'||a[i-1]=='/'||a[i-1]=='^')
			{
				a.erase(i,1);
			v[i]=1;
			i--;
			}
		}
		else if(f[a[i]]!=0)
		{
			if(a[i]!='('&&a[i]!=')')
			{
				while(!s.empty())
				{
					if(f[s.top()]>f[a[i]])break;
					b+=s.top(); 
					s.pop();
				}
				s.push(a[i]);
			}
			else if(a[i]==')'&&flag==1)
			{
				while(!s.empty())
				{
					if(s.top()=='(')break;
					b+=s.top(); 
					s.pop();
				}
				s.pop();
				flag=0;
			}
			else s.push(a[i]),flag=1;
		}
		else b+=a[i];
	}
	while(!s.empty())
	{
		if(s.top()!='('&&s.top()!=')')b+=s.top();
		s.pop();
	}
	
//	cout<<b;
//for(int i=0;i<b.size();i++)cout<<v[i]<<' ';
	for(int i=0;i<b.size();i++)
	{
		if(b[i]>='0'&&b[i]<='9')s2.push(b[i]-'0'),s3.push(i);
		else
		{
//			cout<<1;
			int n=s2.top();
//			cout<<1;
			if(!s3.empty())
			{
				if(v[s3.top()]==1)n*=-1;
				s3.pop();
			}
//			cout<<1;
			s2.pop();
//			cout<<1;
			
//			cout<<1;
			int m=s2.top();
			if(!s3.empty())
			{
				if(v[s3.top()]==1)m*=-1;
				s3.pop();
			}
			s2.pop();
			
//			cout<<n<<' '<<m<<endl;
			if(b[i]=='+')s2.push(n+m);
			else if(b[i]=='-')s2.push(m-n);
			else if(b[i]=='*')s2.push(n*m);
			else if(b[i]=='/')s2.push(m/n);
			else if(b[i]=='^')s2.push(pow(m,n));
		}
	}
	cout<<s2.top();
 	return 0;
 }
2024/7/14 15:53
加载中...