hdu1237 简单计算器
一个简单的中缀表达式求值问题,对每一行单独处理,操作数与运算符交替读入处理即可。
#include <iostream>
#include <iomanip>
#include <sstream>
#include <stack>
#include <string>
using namespace std;
stack<double> num;
stack<char> op;
void calc()
{
double b = num.top(); num.pop();
double a = num.top(); num.pop();
char c = op.top(); op.pop();
double t;
switch(c)
{
case '+': t = a+b; break;
case '-': t = a-b; break;
case '*': t = a*b; break;
case '/': t = a/b; break;
}
num.push(t);
}
int prio(char c)
{
switch(c)
{
case '+':
case '-': return 1;
case '*':
case '/': return 2;
default: return 0;
}
}
int main()
{
string buf;
op.push('#');
cout << setprecision(2) << fixed;
while (getline(cin, buf)) {
if (buf == "0") break;
istringstream sin(buf);
double t;
char c;
sin >> t;
num.push(t);
while (sin >> c >> t) {
while (prio(c) <= prio(op.top())) calc();
op.push(c);
num.push(t);
}
while (op.size() > 1) calc();
// cout << num.top() << endl; // 很奇怪,为什么用这个就WA,41行明明设置了精度。
printf("%.2f\n", num.top()); // 看来还是printf的精度控制更靠谱
num.pop();
}
return 0;
}

浙公网安备 33010602011771号