跳到正文

学习·文化课

P10473 表达式计算4 80分,求救,必关

baixianyi约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年8月9日
更新
2026年10月27日
篇幅
约 5 分钟
获赞
1

版本

  1. v1当前

提交记录

C++
#include<bits/stdc++.h>
using namespace std;
string s;
stack<char> c;
queue<char> q;
stack<long long> j;
bool h_1(){
	return (c.top()=='+'||c.top()=='-'||c.top()=='(');
}
bool h_2(){
	return (c.top()=='*'||c.top()=='/');
}
bool h_3(){
	return c.top()=='^';
}
bool h_4(){
	return c.top()=='(';
}
void qpcp(){
	q.push(c.top());
	c.pop();
}
int np(){
	int z=0;
	while(!q.empty()&&q.front()!='.'){
		z+=q.front()-'0';
		z*=10;
		q.pop();
	}
	z/=10;
	q.pop();
	return z;
}
int nl(int x){
	while(s[x]>='0'&&s[x]<='9'){
		q.push(s[x]);
		x++;
	}
	q.push('.');
	return x;
}
int main(){
	cin>>s;
	for(int i=0;i<s.size();i++){
		if(s[i]>='0'&&s[i]<='9'){
			i=nl(i)-1;
		}else if(s[i]=='+'){
			if(c.empty()||h_1()) c.push(s[i]);
			else{
				while(!c.empty()&&!h_1()){
					qpcp();
				}
				c.push(s[i]);
			}
		}else if(s[i]=='*'||s[i]=='/'){
			if(c.empty()||h_1()||h_2()) c.push(s[i]);
			else{
				while(!c.empty()&&!h_1()&&!h_2()){
					qpcp();
				}
				c.push(s[i]);
			}
		}else if(s[i]=='^'){
			if(c.empty()||h_1()||h_2()||h_3()){
				c.push(s[i]);
			}else{
				while(!c.empty()&&!h_4()){
					qpcp();
				}
				c.push(s[i]);
			}
		}else if(s[i]==')'){
			while(!c.empty()&&!h_4()){
				qpcp();
			}
			if(!c.empty()&&c.top()=='(') c.pop();
		}else if(s[i]=='('){
			c.push(s[i]);
		}else if(s[i]=='-'){
			if(i>0&&(s[i-1]>='0'&&s[i-1]<='9'||s[i-1]==')')){
				if(c.empty()||h_1()) c.push(s[i]);
				else{
					while(!c.empty()&&!h_1()){
						qpcp();
					}
					c.push(s[i]);
				}
			}else{
				q.push('0');
				q.push('.');
				c.push('-');
			}
		}
	}
	while(!c.empty()) qpcp();
	while(!q.empty()){
		if(q.front()>='0'&&q.front()<='9'){
			j.push(np());
		}else if(q.front()=='+'){
			int t=0;
			t=j.top();
			j.pop();
			t+=j.top();
			j.pop();
			j.push(t);
			q.pop();
		}else if(q.front()=='-'){
			int t=0,z=0;
			t=j.top();
			j.pop();
			z=j.top();
			j.pop();
			j.push(z-t);
			q.pop();
		}else if(q.front()=='*'){
			int t=0;
			t=j.top();
			j.pop();
			t*=j.top();
			j.pop();
			j.push(t);
			q.pop();
		}else if(q.front()=='/'){
			int t=0,z=0;
			t=j.top();
			j.pop();
			z=j.top();
			j.pop();
			j.push(z/t);
			q.pop();
		}else if(q.front()=='^'){
			int t=1,a,b=j.top();
			j.pop();
			a=j.top();
			j.pop();
			for(int i=1;i<=b;i++){
				t*=a;
			}
			j.push(t);
			q.pop();
		}else if(q.front()=='('){
			q.pop();
		}
	}
	if(!j.empty()) cout<<j.top();
	return 0;
}
原文