CSU 1655 文本计算器

Description

 Bob讨厌复杂的数学运算.
看到练习册上的算术题,Bob很是头痛.
为了完成作业,Bob想要你帮忙写一个文本版的四则运算计算器.
这个计算器的功能需求十分简单,只要可以处理加减乘除和括号就可以了.
你能够帮助Bob吗?

Input

每个样例一行,输入一个长度小于1500的包含有'(',')','+','-','*','/',和'1'~'9'组成的四则运算表达式.
对于每个样例,参与运算数字在0~10000之间,表达式运算的结果在double的表示范围内.

Output

对于每一个例子,输出表达式的计算结果,精确到小数点后4位

Sample Input

3928*3180*3229+2137
2477*8638
1535+7452+3780+2061*280/3070/(7828-9348)

Sample Output

40333570297.0000
21396326.0000

12766.8763

#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
#include<map>
#include<cmath>
#include<stack>
#include<algorithm>
using namespace std;
const int maxn = 100005;
char s[maxn];

int main()
{
	while (scanf("%s", s) != EOF)
	{
		stack<double> p;
		stack<char> d;
		for (int i = 0; s[i]; i++)
		{
			if (s[i] >= '0'&&s[i] <= '9')
			{
				double u = 0;
				while (s[i] >= '0'&&s[i] <= '9') u = u * 10 + s[i++] - '0';
				p.push(u);	i--;
			}
			else
			{
				if (d.empty() || s[i] == '(') d.push(s[i]);
				else
				{
					if (s[i] == ')')
					{
						while (d.top() != '(')
						{
							double x = p.top();	p.pop();
							double y = p.top(); p.pop();
							if (d.top() == '*') p.push(y * x);
							if (d.top() == '/') p.push(y / x);
							if (d.top() == '+') p.push(y + x);
							if (d.top() == '-') p.push(y - x);
							d.pop();
						}
						d.pop();
					}
					else
					{
						if (d.top() != '(')
						if (s[i] == '+' || s[i] == '-')
						{
							while (!d.empty() && d.top() != '(')
							{
								double x = p.top();	p.pop();
								double y = p.top(); p.pop();
								if (d.top() == '*') p.push(y * x);
								if (d.top() == '/') p.push(y / x);
								if (d.top() == '+') p.push(y + x);
								if (d.top() == '-') p.push(y - x);
								d.pop();
							}
						}
						else if (d.top() == '*' || d.top() == '/')
						{
							double x = p.top();	p.pop();
							double y = p.top(); p.pop();
							if (d.top() == '*') p.push(y * x);
							if (d.top() == '/') p.push(y / x);
							if (d.top() == '+') p.push(y + x);
							if (d.top() == '-') p.push(y - x);
							d.pop();
						}
						d.push(s[i]);
					}
				}
			}
		}
		while (!d.empty())
		{
			double x = p.top();	p.pop();
			double y = p.top(); p.pop();
			if (d.top() == '*') p.push(y * x);
			if (d.top() == '/') p.push(y / x);
			if (d.top() == '+') p.push(y + x);
			if (d.top() == '-') p.push(y - x);
			d.pop();
		}
		printf("%.4lf\n", p.top());
	}
	return 0;
}


你可能感兴趣的:(GSU)