首页 > 其他 > 详细

表达式计算

时间:2017-04-06 21:10:56      阅读:180      评论:0      收藏:0      [点我收藏+]

计算一个包含+ - * / ( ) 的合法表达式的值

思路:数字栈num,运算符栈op。当前操作符优先级不大于栈顶操作符优先级,则数字栈num和运算符栈op出栈,处理后的数字和当前运算符继续与栈顶操作符比较,直至当前运算符的优先级大于栈顶,处理后的数字和当前运算符入栈。

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
using namespace std;
const int maxn=1000;
stack<int>num;
stack<char>op;
char s[maxn];
map<char,int>sign;
void init(int n)
{
    s[n]=#;
    while(!num.empty()) num.pop();
    while(!op.empty()) op.pop();
    op.push(#);
}
int main()
{
    sign[#]=0;
    sign[(]=sign[)]=1;
    sign[+]=sign[-]=2;
    sign[*]=sign[/]=3;
    scanf("%s",s);
    int n=strlen(s);
    init(n);
    int x=0;
    for(int i=0; i<=n; i++)
    {
        if(0<=s[i]&&s[i]<=9) x=x*10+(s[i]-0);
        else if(s[i]==() op.push(s[i]);
        else
        {
            while(sign[op.top()]>=sign[s[i]])
            {
                char f=op.top(); op.pop();
                if(f==(&&s[i++]==)) continue;
                if(f==#&&s[i]==#) break;
                int fig=num.top(); num.pop();
                //cout<<fig<<" "<<f<<" "<<x<<" ";
                if(f==+) x=fig+x;
                else if(f==-) x=fig-x;
                else if(f==*) x=fig*x;
                else if(f==/) x=fig/x;
                //cout<<x<<endl;
            }
            num.push(x);
            op.push(s[i]);
            x=0;
        }
    }
    cout<<num.top()<<endl;
    return 0;
}

 

表达式计算

原文:http://www.cnblogs.com/GeekZRF/p/6675190.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!