简单四则运算的实现
问题描述:
代码如下:
View Code
1 #include <iostream>
2 #include <stack>
3 using namespace std;
4
5 int calculate(int len,char *expStr)
6 {
7 stack<char> st;
8 for(int i=0;i<len;)
9 {
10 if(expStr[i] != '*' && expStr[i] != '/')
11 {
12 st.push(expStr[i]); i++;
13 }
14 else
15 {
16 char t = st.top();
17 st.pop();
18 if(expStr[i] == '*')
19 {
20 t = (t - '0') * (expStr[i+1] - '0');
21 t = t + '0';
22 st.push(t);
23 }
24 else if(expStr[i] == '/')
25 {
26 t = (t-'0') / (expStr[i+1] - '0');
27 t = t + '0';
28 st.push(t);
29 }
30 i = i +2;
31 }
32 }
33
34 if(st.size() == 1) return st.top()-'0';
35
36 char sum;
37 while(!st.empty())
38 {
39 char rva = st.top(); st.pop();
40 char fuhao = st.top(); st.pop();
41 char lva = st.top(); st.pop();
42 if(fuhao == '+')
43 sum = (lva - '0') + (rva - '0');
44 else if(fuhao == '-')
45 sum = (lva - '0') - (rva - '0');
46 if(st.empty())
47 break;
48 else
49 {
50 sum = sum + '0';
51 st.push(sum);
52 }
53 }
54 return sum;
55 }
56 void main()
57 {
58 char expStr[100];
59 cin >> expStr;
60 int len = strlen(expStr);
61
62 cout << calculate(len,expStr) << endl;
63 }