码迷,mamicode.com
首页 > 编程语言 > 详细

简单计算器(使用C++的栈)

时间:2015-06-30 10:04:50      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<cstdlib>
  4 #include<stack>
  5 using namespace std;
  6 int isop(char c)
  7 {
  8     if (c == + || c == - || c == * || c == / || c == ( || c == )||c==#)
  9         return 1;
 10     else return 0;
 11 }
 12 char pro(char s,char c)
 13 {
 14     switch (s){
 15     case(+):
 16     case(-):
 17         if (c == + || c == -)return >;
 18         else if (c == * || c == /)return <;
 19         else if (c == ()return <;
 20         else if (c == ))return >;
 21         else return >;
 22         break;
 23 
 24     case(*):
 25     case(/):
 26         if (c == + || c == -)return >;
 27         else if (c == * || c == /)return >;
 28         else if (c == ()return <;
 29         else if (c == ))return >;
 30         else return >;
 31         break;
 32     case(():
 33         if (c == ))return =;
 34         else return <;
 35     case()) :
 36         return >;
 37     case(#):
 38         if (c == #)return =;
 39         else return <;
 40     }
 41 }
 42 int oper(int a, char op, int b)
 43 {
 44     if (op == +)return a + b;
 45     else if (op == -)return a - b;
 46     else if (op == *)return a*b;
 47     else if (op == /)return a / b;
 48 }
 49 int main()
 50 {
 51     char ch,op;
 52     int i,a,b,res;
 53     stack<int>opn;
 54     stack<char>opt;
 55     ch = getchar();
 56     opt.push(#);
 57     while (ch != #||opt.top() != #)
 58     {
 59         if (!isop(ch))
 60         {
 61             i = atoi(&ch);
 62             ch = getchar();
 63             while (!isop(ch))
 64             {
 65                 i = i * 10 + atoi(&ch);
 66                 ch = getchar();
 67             }
 68             opn.push(i);
 69         }
 70         else 
 71         {
 72             switch (pro(opt.top(), ch))
 73             {
 74             case(<) :
 75                 opt.push(ch);
 76                 ch = getchar();
 77                 break;
 78 
 79             case(=) :
 80                 opt.pop();
 81                 ch = getchar();
 82                 break;
 83 
 84             case(>) :
 85                 op = opt.top();
 86                 opt.pop();
 87                 b = opn.top();
 88                 opn.pop();
 89                 a = opn.top();
 90                 opn.pop();
 91                 res=oper(a, op, b);
 92                 opn.push(res);
 93                 break;
 94             }
 95         }
 96     }
 97     printf("%d\n", opn.top());
 98     system("pause");
 99     return 0;
100 }

 

简单计算器(使用C++的栈)

标签:

原文地址:http://www.cnblogs.com/minimalism/p/4609512.html

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