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;
}