题目:https://cn.vjudge.net/problem/HDU-1237
题意:中文题干不再赘述
思路:由于表达式中不含括号,可以简单处理。
具体方法如下:
开一个符号栈,一个数值栈
先读入一个数放到数值栈中
之后每次分别读一个符号一个数值,若符号为乘除,直接将数值栈栈顶的元素与本次读入的数值进行乘除运算,再放回数值栈中。若符号为加减,则先将符号栈中留存的加减号与数值栈栈顶的两个数进行运算,放回栈中,再将本次读入的符号和数值分别放入符号栈和数值栈。
我为了省去对最后栈中剩下的运算符再做运算,在表达式后拼了一个" + 0"的字符串,这样可以不影响结果又省去一些代码,数值栈底的数值即为答案。
代码:C++
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <stack>
#include <sstream>
using namespace std;
double solve(string &line)
{
stringstream ss(line);
stack<char> opst;
stack<double> nst;
double a;
ss >> a;
nst.push(a);
char op;
while (ss >> op >> a)
{
if (op == '+' || op == '-')
{
while (!opst.empty())
{
char c = opst.top();
opst.pop();
double cur = nst.top();
nst.pop();
nst.top() += (c == '+' ? cur : -cur);
}
opst.push(op);
nst.push(a);
}
else if (op == '*')
{
nst.top() *= a;
}
else //if(op == '/')
{
nst.top() /= a;
}
}
nst.pop();
return nst.top();
}
int main()
{
string line;
while (getline(cin, line) && line != "0")
{
line += " + 0";
printf("%.2f\n", solve(line));
}
return 0;
}