题解 | #简单计算器#
简单计算器
http://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
简单的题还是写了那么多代码。。。
该题注意2个地方:
- 字符串输入,sstream
- 结果的输出,中途用stod将string转为double,保证精度
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <algorithm>
using namespace std;
const int N = 10010;
stack<string> expss;
stack<double> nums;
map<string, int> exps;
//后将要压的exp1和exp2比较
bool pri(string exp1, string exp2)
{
if (exps[exp2] - exps[exp1] > 1)
return true;
else
return false;
}
//计算num1(expt)num2
double cal(string expt, double num1, double num2)
{
double ans = 0;
switch (exps[expt])
{
case 0:
/* code */
ans = num1 * num2;
break;
case 1:
/* code */
ans = num1 / num2;
break;
case 3:
/* code */
ans = num1 + num2;
break;
case 4:
/* code */
ans = num1 - num2;
break;
default:
break;
}
return ans;
}
//循环
double loop(string ss)
{
ss += " ";
ss += "$";
expss.push("#");
istringstream str(ss);
string out;
while (str >> out)
{
if (out == "+" || out == "-" || out == "*" || out == "/" || out == "$")
{
string exp2 = expss.top();
while (!pri(out, exp2))
{
double a = nums.top();
nums.pop();
double b = nums.top();
nums.pop();
double ans = cal(exp2, b, a);
nums.push(ans);
expss.pop();
exp2 = expss.top();
}
if (pri(out, exp2))
{
expss.push(out);
}
if (expss.top() == "$")
break;
}
else
{
nums.push(stod(out));
}
}
if (!nums.empty())
return nums.top();
else
return -37;
}
int main()
{
string ss;
exps["*"] = 0;
exps["/"] = 1;
exps["+"] = 3;
exps["-"] = 4;
exps["$"] = 6;
exps["#"] = 8;
while (getline(cin, ss))
{
if (ss == "0")
break;
double ans = loop(ss);
printf("%.2lf\n", ans);
while (!nums.empty())
nums.pop();
while (!expss.empty())
expss.pop();
}
return 0;
}