-
Notifications
You must be signed in to change notification settings - Fork 0
/
夹杂字母的.cpp
127 lines (106 loc) · 2.07 KB
/
夹杂字母的.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include<iostream>
#include<stack>
using namespace std;
//使用系统自带STL库函数
class calculator{
private:
stack<char> optr;
stack<double> opnd;
double value;
public:
calculator(){
opnd.push(0);
optr.push('#');
}
void run();
void evaluate();
void clear();
private:
int lp(char op);
int rp(char op);
double operate(char theta,double a,double b);
};
//操作具体的方法
double calculator::operate(char theta,double a,double b){
double ret;
switch(theta){
case '+':ret=a+b;break;
case '-':ret=a-b;break;
case '*':ret=a*b;break;
case '/':ret=a/b;break;
}
return ret;
}
int calculator::lp(char ch){
int ret;
switch(ch){
case '+':ret=3;break;
case '-':ret=3;break;
case '*':ret=5;break;
case '/':ret=5;break;
case '(':ret=1;break;
case ')':ret=6;break;
case '#':ret=0;break;
default:ret=-1;
}
return ret;
}
int calculator::rp(char ch){
int ret;
switch(ch){
case '+':ret=2;break;
case '-':ret=2;break;
case '*':ret=4;break;
case '/':ret=4;break;
case '(':ret=6;break;
case ')':ret=1;break;
case '#':ret=0;break;
}
return ret;
}
void calculator::evaluate(){
char ch,op,theta;
double val,a,b;
cin>>ch;
op='#';
//当判断ch结束时 堆栈也是空的时候 结束循环
while((ch!='#')||(op!='#')){
if(((lp(ch)!=-1) ||isdigit(ch))){
if(isdigit(ch)){
cin.putback(ch);
cin>>val;
opnd.push(val);
cin>>ch;
//计算优先级 根据优先级进行判断
}else if(lp(op)<rp(ch)){
optr.push(ch);
cin>>ch;
}else if(lp(op)==rp(ch)){
optr.pop();
cin>>ch;
}else{
theta=optr.top();
optr.pop();
b=opnd.top();
opnd.pop();
a=opnd.top();
opnd.pop();
//运算具体结果
opnd.push(operate(theta,a,b));
}
op=optr.top();
}else{
cin>>ch;
}
}
//判断结果是否正确
if(opnd.top()==0){
cout<<"错误";
} else{
cout<<"="<<opnd.top();
}
}
int main(){
calculator c;
c.evaluate();
}