题目1019:简单计算器

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


水题调试了接近一个小时=。=
双栈来模拟计算器的+-*/

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

int main(void)
{
	map<char, int>Map;//定义+-*/执行顺序
	Map.insert(make_pair('+', 1));
	Map.insert(make_pair('-', 1));
	Map.insert(make_pair('*', 2));
	Map.insert(make_pair('/', 2));

	stack<double>stad;
	stack<char>stach;
	int x;
	string str;
	double y, z;
	while (getline(cin, str))
	{
		if (str == "0")
		{
			break;
		}
		while (!stad.empty())
		{
			stad.pop();
		}
		while (!stach.empty())
		{
			stach.pop();
		}
		x = 0;
		for (string::size_type i = 0; i < str.size(); i++)
		{
			if(str[i] == ' ')
			{
				continue;
			}
			else if (str[i] >= '0' && str[i] <= '9')
			{
				if((i != str.size() - 1 && str[i+1] == ' ') || i == str.size() - 1)
				{
					x = x * 10 + str[i] - '0';
					stad.push(x * 1.0);
					x = 0;
				}
				else
				{
					x = x * 10 + str[i] - '0';
				}
			}
			else
			{
				while (!stach.empty() && Map[str[i]] <= Map[stach.top()])
				{
					y = stad.top(); stad.pop();
					z = stad.top(); stad.pop();
					switch (stach.top())
					{
					case '+' :
						stad.push(z + y);
						break;
					case '-' :
						stad.push(z - y);
						break;
					case '*' :
						stad.push(z * y);
						break;
					case '/' :
						stad.push(z / y);
						break;
					default:
						break;
					}
					stach.pop();
				}
				stach.push(str[i]);
			}

		}//for

		/*while (!stad.empty())
		{
			cout << stad.top() << endl;
			stad.pop();
		}
		while (!stach.empty())
		{
			cout << stach.top() << endl;
			stach.pop();
		}*/

		while (!stach.empty())
		{
			y = stad.top(); stad.pop();
			z = stad.top(); stad.pop();
			switch (stach.top())
			{
			case '+' :
				stad.push(z + y);
				break;
			case '-' :
				stad.push(z - y);
				break;
			case '*' :
				stad.push(z * y);
				break;
			case '/' :
				stad.push(z / y);
				break;
			default:
				break;
			}
			stach.pop();
		}
		//cout << stad.size() << endl;
		cout << fixed << setprecision(2) << stad.top() << endl;
	}
	return 0;
}


Keep it simple!
作者:N3verL4nd
知识共享,欢迎转载。
原文地址:https://www.cnblogs.com/lgh1992314/p/5834824.html