-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntCalculator.c
More file actions
162 lines (157 loc) · 2.5 KB
/
IntCalculator.c
File metadata and controls
162 lines (157 loc) · 2.5 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/*采用数组栈简单实现带括号加减乘除表达式运算*/
#include <stdio.h>
#include <stdlib.h>
// 获取一行字符串
void GetStr(char s[])
{
int i = 0;
while(1)
{
s[i] = getchar();
if(s[i] == '\n') break;//回车符结束
if(s[i] == '\b')//退格符处理
{
if(i != 0) i--;
continue;
}
i++;
}
}
// 两数简单计算
int Calculate(int a, char operation, int b)
{
int result;
if(operation == '+')
{
result = a+b;
}
else if(operation == '-')
{
result = a-b;
}
else if(operation == '*')
{
result = a*b;
}
else if(operation == '/')
{
if(b == 0)
{
printf("Division by zero!\n");
return 0;
}
result = a/b;
}
else if(operation == '%')
{
if(b == 0)
{
printf("Division by zero!\n");
return 0;
}
result = a%b;
}
return result;
}
// 运算符优先级
int OperatorPrecedence(char operation)
{
if(operation == '(' || operation == ')')
{
return 1;
}
else if(operation == '*' || operation == '/' || operation == '%')
{
return 3;
}
else if(operation == '+' || operation == '-')
{
return 4;
}
else
{
return 15;
}
}
// 含括号+-*/%表达式计算
int Calculator(char* s)
{
int ds[32], n;
char cs[32];
int i, dtop = 0, ctop = 0;
char* nend;
for(i=0; s[i]!='\n'; i++)
{
if(s[i]>='0' && s[i]<='9')
{
//读取一个数字
n = strtol(s+i, &nend, 0);
i = nend-s-1;
ds[dtop] = n;
dtop++;
}
if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' || s[i] == '%'
|| s[i] == '(')
{
if(s[i] == '-')
{
if(i == 0 || s[i-1] == '(')//(-n) -> (0-n)
{
ds[dtop] = 0;
dtop++;
}
}
if(s[i] == '(')//n() -> n*()
{
if(i > 0 && s[i-1]>='0' && s[i-1]<='9')
{
cs[ctop] = '*';
ctop++;
}
}
if(ctop > 0 && cs[ctop-1] != '(' && dtop > 1
&& OperatorPrecedence(s[i]) >= OperatorPrecedence(cs[ctop-1]))
{
n = Calculate(ds[dtop-2], cs[ctop-1], ds[dtop-1]);
dtop -= 2;
ctop--;
ds[dtop] = n;
dtop++;
}
cs[ctop] = s[i];
ctop++;
}
if(s[i] == ')')
{
while(ctop > 0 && cs[ctop-1] != '(')
{
n = Calculate(ds[dtop-2], cs[ctop-1], ds[dtop-1]);
dtop -= 2;
ctop--;
ds[dtop] = n;
dtop++;
}
if(ctop > 0 && cs[ctop-1] == '(') ctop--;
}
}
while(ctop > 0 && dtop > 1)
{
n = Calculate(ds[dtop-2], cs[ctop-1], ds[dtop-1]);
dtop -= 2;
ctop--;
ds[dtop] = n;
dtop++;
}
return ds[dtop-1];
}
int main()
{
char s[64];
while(1)
{
printf("[Calculator]>");
GetStr(s);//5+4*2\n
printf("=%d\n", Calculator(s));
}
return 0;
}