HDU1237 简单计算器 (STL)

HDU1237 简单计算器 (STL)

题目

读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36

AC代码

#include<iostream>
#include<algorithm>
#include<stack>
#include<map>
#include<cstring>
using namespace std;
stack<double> num;
stack<char> op;
string s,s1;
map<char,int> h;
void eval()
{
	double b=num.top();
	num.pop();
	
	double a=num.top();
	num.pop();
	
	char p=op.top();
	op.pop();
	
	double r;
	if(p=='+') r=a+b;
	else if(p=='-') r=a-b;
	else if(p=='*') r=a*b;
	else if(p=='/') r=a/b;
	
	num.push(r);
}
int main()
{
	h['+']=1; h['-']=1;
	h['*']=2; h['/']=2;
	while(getline(cin,s1))
	{
		if(s1=="0") break;
		
		s.clear();
		for(int i=0;i<s1.size();i++)
		{
			if(s1[i]!=' ')
				s+=s1[i];	
		} 
//		cout<<s<<endl;

		for(int i=0;i<s.size();i++)
		{
			if(isdigit(s[i]))
			{
				double sum=0;
				while(isdigit(s[i]))
				{
					sum=sum*10+(s[i]-'0');
					i++;
				}

				num.push(sum);
				i--;
			}
			else
			{
				while(op.size() && h[op.top()]>=h[s[i]])
					eval();
				op.push(s[i]);
			}
			
		}
		
		while(op.size())
			eval();
		
		printf("%.2lf\n",num.top());		
	}
	return 0;
}
posted @ 2021-07-12 17:15  斯文~  阅读(43)  评论(0)    收藏  举报

你好!