基本四则运算实现

 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 stack<char> optr;
 5 stack<int> opnd;
 6 int oplevel(char op)
 7 {
 8     if(op=='=')
 9     {
10         return 0;
11     }
12     else if(op=='+'||op=='-')
13     {
14         return 1;
15     }
16     else if(op=='*'||op=='/')
17     {
18         return 2;
19     }
20     else
21     {
22         return -1;
23     }
24 }
25 bool precede(char opa,char opb)
26 {
27     return oplevel(opa)>=oplevel(opb);
28 }
29 int calculate(int a,char op,int b)
30 {
31     if(op=='+')
32     {
33         return a+b;
34     }
35     else if(op=='-')
36     {
37         return a-b;
38     }
39     else if(op=='*')
40     {
41         return a*b;
42     }
43     else if(op=='/')
44     {
45         if(b!=0) return a/b;
46         else return 0;
47     }
48     else
49     {
50         return 0;
51     }
52 }
53 int main()
54 {
55     optr.empty();
56     opnd.empty();
57     optr.push('=');
58     char *exp=(char *)malloc(20*sizeof(char));
59     cin>>exp;
60     int i=0;
61     while(exp[i]!='=' || optr.top()!='=')
62     {//1+3*2-9/3=
63         if(exp[i]>='0'&&exp[i]<='9')
64         {
65             opnd.push(exp[i]-'0');
66         }
67         else
68         {
69             while(optr.top()!='=' && precede(optr.top(),exp[i]))
70             {
71                 int a,b;
72                 b=opnd.top();
73                 opnd.pop();
74                 a=opnd.top();
75                 opnd.pop();
76                 a=calculate(a,optr.top(),b);
77                 optr.pop();
78                 opnd.push(a);
79             }
80             if(exp[i]=='=') break;
81             optr.push(exp[i]);
82         }
83         i++;
84     }
85     cout<<opnd.top()<<endl;
86     return 0;
87 }

 

转载于:https://www.cnblogs.com/TYcnblogs/p/four_arithmetic_operation.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值