题解 | 计算表达式

#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;
	}
}

全部评论

相关推荐

点赞 评论 收藏
分享
ResourceUt...:你是我见过最美的牛客女孩
晒一下我的毕业照
点赞 评论 收藏
分享
05-29 20:34
门头沟学院 C++
KarlAllen:得做好直接春招的准备。学历差的话,一是面试要求会比学历好的严格不少,二是就算面试通过了也会被排序。总之暑期和秋招对于学历差的就是及其不友好
无实习如何秋招上岸
点赞 评论 收藏
分享
兄弟们,实习都是在接各种api,该怎么包装简历
仁者伍敌:感觉我自己做小项目也是各种api啊,我要怎么包装简历
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务