题解 | 计算表达式

#include<iostream>
#include<stack>
#include<string>
#include<cctype>
using namespace std;
int Priority(char c){
	if(c=='#')
	    return 0;
	else if(c=='$')
	    return 1;
	else if(c=='+'||c=='-')
	    return 2;
	else
	    return 3;
}
float Getnumber(string s,int& index){
    float number=0;
	while(isdigit(s[index])){
		number=number*10+s[index]-'0';
		index++;
	}
	return number;
}
float Calculate(float x,float y,char op){
	float result=0;
	if(op=='+')
	    result=x+y;
	else if(op=='-')
	    result=x-y;
	else if(op=='*')
	    result=x*y;
	else if(op=='/')
	    result=x/y;
	return result;
}
int main(){
	string s;
	stack<float> data;
	stack<char> oper;
	oper.push('#');
	while(cin>>s){
		s+='$';
		int i=0;
		while(i<s.size()){
			if(isdigit(s[i])){
				data.push(Getnumber(s,i));
				
			}
			else{
				if(Priority(s[i])>Priority(oper.top())){
                    oper.push(s[i]);
					i++;
				}
				else{
					double y=data.top();
					data.pop();
					double x=data.top();
					data.pop();
					data.push(Calculate(x,y,oper.top()));
					oper.pop();
				}

			}
		}
		cout<<data.top()<<endl;
	}
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务