简单四则运算的实现

问题描述:

 

代码如下:

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 }

 

转载于:https://www.cnblogs.com/xuxu8511/archive/2012/03/30/2425789.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值