码迷,mamicode.com
首页 > 其他好文 > 详细

基本四则运算实现

时间:2015-09-18 20:17:17      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

 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 }

 

基本四则运算实现

标签:

原文地址:http://www.cnblogs.com/TYcnblogs/p/four_arithmetic_operation.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!