HDU-1237-简单计算器

HDU-1237-简单计算器

传送门

这道题是一道栈的运用

中文题目,我就不描述啦~
按照计算法则,是先乘除,后加减。(但实际上计算器是实时计算的)
因为是合法的表达式,运算符和操作数之间只有一个空格。所以碰到一个运算符的话那么前后就是操作数。碰到加号将下一个数入栈,碰到减号将下一个数变成他的相反数入栈,碰到乘号和除号就弹出一个数与操作符的下一个数进行运算即可。

因为我是getline读入,所以注意一个非负整数不止一位。

代码部分:

#include <bits/stdc++.h>
using namespace std;

string str;
stack<double> s;
double ans;

int main()
{
	while (1)
	{
		ans = 0;
		while (!s.empty())
		{
			s.pop();
		}
		getline(cin, str);
		int n = str.size();
		if (str[0] == '0' && n == 1)
		{
			break;
		}
		for (int i = 0; i < n; i++)
		{
			double temp = 0;
			if (str[i] == ' ')
			{
				continue;
			}
			if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/')
			{
				if (str[i] == '+')
				{
					i += 2;
					while (i < n && str[i] != ' ')
					{
						temp = temp * 10 + (str[i] - '0');
						i++;
					}
					s.push(temp);
				}
				else if (str[i] == '-')
				{
					i += 2;
					while (i < n && str[i] != ' ')
					{
						temp = temp * 10 + (str[i] - '0');
						i++;
					}
					s.push(-temp);
				}
				else if (str[i] == '*')
				{
					i += 2;
					double t1 = s.top();
					s.pop();
					while (i < n && str[i] != ' ')
					{
						temp = temp * 10 + (str[i] - '0');
						i++;
					}
					double t2 = temp;
					double t = t1 * t2;
					s.push(t);
				}
				else
				{
					i += 2;
					double t1 = s.top();
					s.pop();
					while (i < n && str[i] != ' ')
					{
						temp = temp * 10 + (str[i] - '0');
						i++;
					}
					double t2 = temp;
					double t = 1.0 * t1 / t2;
					s.push(t);
				}
			}
			else
			{
				while (str[i] != ' ')
				{
					temp = temp * 10 + (str[i] - '0');
					i++;
				}
				s.push(temp);
			}
		}
		while (!s.empty())
		{
			ans += s.top();
			s.pop();
		}
		printf ("%.2f\n", ans);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

娃娃酱斯密酱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值