-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path100000602-00.cpp
69 lines (64 loc) · 2.03 KB
/
100000602-00.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* hint:
*
* 本体并没有按常规解法来做。
* 而是将求解中缀表达式和计算结果两个过程融合在一起来进行了。
*/
#include <stack>
#include <string>
#include <iostream>
#include <map>
using namespace std;
map<char, int> sign_priority = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
int main()
{
while (true)
{
string line;
getline(cin, line);
if (line.length() == 1 && line[0] == '0') break;
stack<char> sign;
stack<double> ans;
// parse a line
for (int i = 0; i < line.length(); i++)
{
if ('0' <= line[i] && line[i] <= '9')
{
int num = 0;
while (i < line.length() && '0' <= line[i] && line[i] <= '9')
num = num * 10 + line[i++] - '0';
ans.push(num);
}
if (line[i] == '+' || line[i] == '-' || line[i] == '*' || line[i] == '/')
{
if (sign.empty())
sign.push(line[i]);
else if (sign_priority[line[i]] <= sign_priority[sign.top()])
{
double b = ans.top(); ans.pop();
double a = ans.top(); ans.pop();
if (sign.top() == '+') ans.push(a + b);
if (sign.top() == '-') ans.push(a - b);
if (sign.top() == '*') ans.push(a * b);
if (sign.top() == '/') ans.push(a / b);
sign.pop();
i--;
}
else
sign.push(line[i]);
}
}
while (!sign.empty())
{
double b = ans.top(); ans.pop();
double a = ans.top(); ans.pop();
if (sign.top() == '+') ans.push(a + b);
if (sign.top() == '-') ans.push(a - b);
if (sign.top() == '*') ans.push(a * b);
if (sign.top() == '/') ans.push(a / b);
sign.pop();
}
printf("%.2lf\n", ans.top());
}
return 0;
}