题解 | #计算表达式#

计算表达式

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

和简单计算器一模一样直接搬过来用了
#include<iostream>
#include<cstdio>
#include<stack>
#include<map>
#include<string>
using namespace std;

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

float getnum(int &index, string str) {  //将字符串化为整数
	float res = 0;
	while (str[index] >= '0' && str[index] <= '9') {
		res = res * 10 + str[index++] - '0';
	}
	return res;

}

float res(float a, float b, char c) {
	if (c == '+')
		return a + b;
	else if (c == '-')
		return a - b;
	else if (c == '*')
		return a * b;
	else 
		return a / b;

}


int main() 
{
	string str;
	while (getline(cin , str)) 
	{
		stack<float> num;
		stack<char> oper;   //分别标识数字栈和符号栈

		for (int i = 0; i < str.size(); i++) 
		{
			if (str[i] >= '0' && str[i] <= '9') 
			{
				num.push(getnum(i, str));
			}
			if (str[i] == '+' || str[i] == '-'||str[i] == '*'||str[i] == '/')
			{
				if (!oper.empty())
				{	
					if(priority[oper.top()] >= priority[str[i]])
					{
						while(priority[oper.top()] >= priority[str[i]] ) {  //将优先级高的全部弹出
							char c = oper.top();  oper.pop();  //弹出符号
							float b = num.top();   num.pop();		//弹出数字a
							float a = num.top();   num.pop();		//弹出数字b
							num.push(res(a, b, c));
							if (oper.empty()) break;
						}
						oper.push(str[i]);
					}
					else oper.push(str[i]);
				}
				else oper.push(str[i]);
			}
		}
		while (!oper.empty()) 
		{ 
			char c = oper.top();  oper.pop();  //弹出符号
			float b = num.top();   num.pop();		//弹出数字a
			float a = num.top();   num.pop();		//弹出数字b
			num.push(res(a, b, c));
		}
		printf("%.0f\n", num.top());
	}
}

全部评论

相关推荐

rndguy:个人思路,抛砖引玉。 要我的话我先问清楚需求:要什么精度,什么速度,什么环境。 如果精度要求很低,平台也有点柔性的话,只需要输出pwm,然后开个中断记录各多少个脉冲,如果脉冲时间不对齐了就反馈控制电流加减就行。要求同步要求稍微高点的话可以在脉冲间做个线性插值,同步精度会高些。 但总体来说,如果直流有刷只有脉冲没有好的编码器的话很难做精准定位什么的(除非用一些电机磁路结构相关的奇技淫巧如高频注入什么的),所以要求更高就需要大量参数辨识和校准,那就慢多了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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