-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculatedExpression.cpp
106 lines (105 loc) · 2.44 KB
/
CalculatedExpression.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
#include <cstdio>
#include <string>
#include <stack>
#include <cctype>
using namespace std;
int priority(char c)
{
if (c == '#')
{
return 0;
}
else if (c == '$')
{
return 1;
}
else if (c == '+' || c == '-')
{
return 2;
}
else
{
return 3;
}
}
double calculate(double x, double y, char op)
{
double result = 0;
if (op == '+')
{
result = x + y;
}
else if (op == '-')
{
result = x - y;
}
else if (op == '*')
{
result = x * y;
}
else if (op == '/')
{
result = x / y;
}
return result;
}
double getnum(string s, int &i)
{
double data = 0;
while (isdigit(s[i]))
{
data = data * 10 + s[i] - '0';
i++;
}
return data;
}
int main(int argc, char const *argv[])
{
string s;
while (getline(cin, s))
{
if (s == "0")
{
break;
}
int i = 0; // 表示扫描表达式时的下标
stack<char> operation; // 运算符栈
stack<double> num; // 运算数栈
s += '$'; // 字符串末尾增加一个字符标志
operation.push('#');
while (i < s.size())
{
if (s[i] == ' ')
{
i++;
}
else if (isdigit(s[i]))
{
// cout << s[i] << " ";
num.push(getnum(s, i));
}
else
{ // 扫描到的是字符,且比栈顶的优先级高
if (priority(s[i]) > priority(operation.top()))
{
operation.push(s[i]); // 扫描到的字符优先级高,压入栈中
i++; // 继续扫描
}
else
{ // 弹出栈顶元素,并和运算数栈顶的两个数字进行运算
double y = num.top();
num.pop();
double x = num.top();
num.pop();
num.push(calculate(x, y, operation.top()));
// 将运算结果压入栈顶
operation.pop();
}
}
}
cout << num.top() << endl;
// printf("%.2f\n", num.top());
}
return 0;
}