zoukankan      html  css  js  c++  java
  • 前缀表达式计算(栈的使用)

    #include <bits/stdc++.h>
    using namespace std;
    string s;
    stack<double>ac;
    bool op(char c){
        if(c=='+'||c=='-'||c=='*'||c=='/'){
            return 1;
        }
        else return 0;
    }
    int main(){
            getline(cin,s);
            while(!ac.empty()){
                ac.pop();
            }
            int len=s.length();
            int n=1;
            double num=0;
            int flag=0;
            for(int i=len-1;i>=0;i--){
                if(s[i]>='0'&&s[i]<='9'){
                    num+=(s[i]-'0')*n;
                    n*=10;
                }
                else if(s[i]=='.'){
                    num=num/(n*1.0);
                    n=1;
                }
                else if((s[i]=='+'||s[i]=='-')&&num!=0){
                    if(s[i]=='+'){
                        ac.push(num);
                        i--;
                        continue;
                    }
                    else{
                        num=-num;
                        ac.push(num);
                        i--;
                        continue;
                    }
                }
                else if(s[i]==' '){
                    ac.push(num);
                    num=0;
                    n=1;
                    continue;
                }
                else if(op(s[i])){
                    double a=ac.top();
                    ac.pop();
                    double b=ac.top();
                    ac.pop();
                    double t=0;
                    if(s[i]=='+'){
                        t=a+b;
                    }
                    else if(s[i]=='-'){
                        t=a-b;
                    }
                    else if(s[i]=='*'){
                        t=a*b;
                    }
                    else if(s[i]=='/'){
                        if(b==0){
                            flag=1;
                            break;
                        }
                        t=a/b;
                    }
                    ac.push(t);
                    i--;
                }
            }
            if(flag==0){
                printf("%.1f ",ac.top());
            }
            else{
                printf("ERROR ");
            }
        return 0;
    }

  • 相关阅读:
    被遗忘的Ruby Web开发框架
    批处理设置IP地址
    Java集合类ArrayList,Vector,HashMap,Hashtable区别
    eclipse安装Eclipse HTML Editor插件
    安装MYSQL向导时,到最后一步 Mysql server instance configuration wizard 单击完成时没反响应?
    各种缓存综述
    linux下apache字符集问题
    ubuntu下图形界面软件问题综述
    linux1xh3c802.11在ubuntu下联网
    REMOTE_ADDR,HTTP_CLIENT_IP,HTTP_X_FORWARDED_FOR
  • 原文地址:https://www.cnblogs.com/lhlccc/p/12382836.html
Copyright © 2011-2022 走看看