hdu1237简单计算器

简单计算器

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10383    Accepted Submission(s): 3345


Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
 

Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
 

Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
 

Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
 

Sample Output
3.00 13.36
 
搞了一天吧。。。这道题。最后还是参考了网上的代码AC的。。。哎。失败。不过有时候自己闭门造车确实是行不通的。看别人的代码确实长了不少知识。。不过以后还是尽量原创的好。之所以要转载这篇代码。主要是自己吸取了不少教训,做个纪念了(其实是怕自己把犯过的错误再犯一遍。。。。)。确实c++我不熟。其实这道题可以不用栈的。网上有c语言写的40行代码。。相当牛b了。。不过我这是为了练习栈。所以应该用用栈。。
#include<iostream>
#include<cstdio>
#include<string>
#include<stack>
using namespace std;

int main()
{
	string str;
	while(getline(cin,str)&&str!="0")//getline这回事。。我又忘了。。果然还是c语言里面的gets好用啊。。
	{
		int len=str.length();
		stack<double>S,SS;
		stack<char>s,ss;
		for(int i=0;i<len;i++){
			if(str[i]==' ')
				continue;
			else if(str[i]=='*'||str[i]=='/')
			{
				double x=S.top();
				S.pop();
				int j;
				double y=0;
				j=i+2;
				while(str[j]!=' '&&j<len)
				{
					y=y*10+str[j]-'0';
					j++;
				}
				if(str[i]=='*')S.push(x*y);
				else S.push(x/y);
				i=j;
			}
			else if(str[i]=='+'||str[i]=='-')
			{
				s.push(str[i]);
			}
			else 
			{
				int j;
				double x=0;
				for(j=i;j<len;j++)
				{
					if(str[j]!=' ')
					{
						x=x*10+str[j]-'0';
					}
					else 
						break;
				}
				S.push(x);
				i=j;
			}
		}
		while(!S.empty())//一下两个函数是将数字顺序逆置。相当重要啊。因为表达式的左结合性。。
		{
			double x=S.top();
			SS.push(x);
			S.pop();
		}
		while(!s.empty())//当初就是自作聪明删了这两个函数。导致查错查了半天。。
		{
			char ch=s.top();
			ss.push(ch);
			s.pop();
		}
		while(!SS.empty()&&!ss.empty())
		{
			double x1=SS.top();
			SS.pop();
			double x2=SS.top();
			SS.pop();
			char ch=ss.top();
			ss.pop();
			if(ch=='+')
			{
				SS.push(x1+x2);
			}
			else
				SS.push(x1-x2);
		}
		printf("%.2lf\n",SS.top());
	}
	return 0;
}


原文地址:https://www.cnblogs.com/unclejelly/p/4082157.html