zoukankan      html  css  js  c++  java
  • 仿LISP运算 | c++

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 /**
     4  *  仿LISP运算
     5  *  模拟(sub (mul 2 4) (div 9 3))
     6  * @return
     7  */
     8 
     9 int main() {
    10     int mark = 0;
    11     int num1,num2;
    12     string str;
    13     stack<int> numStatck;
    14     stack<string> operStack;
    15 
    16     getline(cin,str);
    17     for(int i = 0; i < str.length() ; i++)
    18     {
    19         char c = str[i];
    20         cout<<c<<" ";
    21         if(c == '(') {
    22             operStack.push(str.substr(i+1,3));
    23             i += 4;
    24             mark =  i + 1;
    25         } else if(c == ')') {
    26             if(mark < i) {
    27                 //stoi string --> int
    28                 numStatck.push(stoi(str.substr(mark,i-mark)));
    29 
    30                 i++;
    31                 mark = i + 1;
    32             }
    33             num1 = numStatck.top();
    34             numStatck.pop();
    35             num2 = numStatck.top();
    36             numStatck.pop();
    37             string ex = operStack.top();
    38             operStack.pop();
    39 
    40             if(ex == "add")
    41                 numStatck.push(num1+num2);
    42             else if(ex == "sub")
    43                 numStatck.push(num1-num2);
    44             else if (ex == "mul")
    45                 numStatck.push(num1*num2);
    46             else if( ex ==  "div")
    47                 if(num2 == 0) cout <<"ERROR"<<endl;
    48                 else
    49                     numStatck.push(num2/num1);
    50 
    51         } else {
    52             if(c == ' ') {
    53                 if(mark < i ) {
    54                     numStatck.push(stoi(str.substr(mark,i-mark)));
    55                     mark = i + 1;
    56                 }
    57             }
    58         }
    59     }
    60     cout<<"结果:";
    61     cout<<numStatck.top()<<endl;
    62     return 0;
    63 }
  • 相关阅读:
    YUM安装(卸载)KDE和GNOME
    shutdown
    linux运行级别
    [root@localhost ~]#各项解释
    常用服务端口号
    部分命令技巧
    网卡配置文件
    《移动端支付系统如何设计有效地防重失效机制?》阅读心得
    软件开发第三天(记录)
    软件开发第二天(记录)
  • 原文地址:https://www.cnblogs.com/jj81/p/11184338.html
Copyright © 2011-2022 走看看