题解 | #计算表达式#化简了点代码

计算表达式

https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <map>
using namespace std;

map<char, int> mymap = {
	{'+', 0},{'-', 0},{'/', 1},{'*', 1}
};

float jisusan(float x, float y, char oper){
	float res;
	switch(oper){
		case '+':
			res = x + y;
			break;
		case '-':
			res = x - y;
			break;
		case '*':
			res = x * y;
			break;
		case '/':
			res = x / y;
			break;
	}
	return res;
}


int main() {
    stack<float> numStack;
    stack<char> operStack; //operator 运算符 
    string expr; //expression 表达式 
    while(getline(cin, expr)){
    	for(int i = 0; i < expr.size(); i++){
    		if(expr[i] >= '0' && expr[i] <= '9'){ 
				//表明这是一个数字 可能有很多位 
				int j = i;
    			while(j < expr.size() && expr[j] >= '0' && expr[j] <= '9'){
    				j++;
    				continue;
				}
				//此时j越界,或者j是操作符 i 到 j - 1为数字
				float num = 0; 
				while(i != j){
					num *= 10;
					num += (expr[i] - '0');
					i++;
				}
				i--;
				numStack.push(num);
			}else{
				//运算符先跟栈里的比较
				//此次的运算符是一定要放进去的 
				while(!operStack.empty() && mymap[operStack.top()] >= mymap[expr[i]]){
				 	//栈顶的优先级 >= 当前的优先级 
					//弹出两个数和操作符计算结果然后放到numstack
					float a1 =  numStack.top();
					numStack.pop();
					float a2 = numStack.top();
					numStack.pop();
					char c = operStack.top();
					operStack.pop();
					float res = jisusan(a2, a1, c);
					numStack.push(res);	
				}

				operStack.push(expr[i]);				
			}	
		}
		//把剩余的都弄出来 
		while(!operStack.empty()){
			float a1 =  numStack.top();
			numStack.pop();
			float a2 = numStack.top();
			numStack.pop();
			char c = operStack.top();
			operStack.pop();
			float res = jisusan(a2, a1, c);
			numStack.push(res);
		}
		float a1 =  numStack.top();
		numStack.pop();
		//printf("%f\n", a1); //这里用cout方便点 
		cout << a1 <<endl;
	
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

hanliu:1. 排版与格式问题字体与对齐问题:标题和内容的字体大小差异不够明显,无法迅速吸引目光。某些文字看起来有些拥挤(比如校园经历中的“班委成员”部分)。2. 内容逻辑性模块顺序问题:实习经历放在较靠后的位置,实际上这部分内容对应聘来说更重要,建议提前突出。细节表述不够突出:比如教育背景部分的专业课程仅仅列出名字,没有说明自己在这些课程中表现如何或者掌握了什么技能,缺乏量化描述。多余内容:例如“班委成员”和“宣传委员”这类校园经历,叙述过于普通,缺乏和岗位相关的实质性贡献。,建议简写。3. 措辞专业性表达不够精准:例如“协助班长与团支书更好地为同学服务”显得较为笼统,没有实际成果的体现。用词重复:如“学习了焊接”“学习了光检”等重复词语较多,缺乏丰富的动词来展示个人能力(如“负责”“优化”“改进”等)。技能展示不足:虽然列出了UG和CAD证书,但没有明确提到这些技能如何在实际工作中发挥作用。4. 技能匹配度技能深度不足:虽然列出了掌握的软件和技术,但没有描述技能水平(如“熟练掌握”“精通”),也没有具体案例支持这些技能。缺乏岗位导向性:比如针对机械设计与制造方向,实习经历提到了“E6尾灯项目”,但没有详细说明自己在其中的技术贡献,可能会显得经验描述泛泛而谈。5. 自我评价问题表达空泛:如“具有良好的沟通协调能力”“责任心强”之类的描述太常见,没有让人眼前一亮的特点。缺乏成果支持:自我评价中的能力没有用具体项目、经历或成就来验证,可信度较弱。 兄弟加油
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务