首页 > 其他 > 详细

前缀,后缀表达式求值

时间:2019-10-19 09:56:36      阅读:57      评论:0      收藏:0      [点我收藏+]

前缀表达式

从右至左扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素 op 次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果

从右至左,遇数压1,遇符弹2,再来计算。

后缀表达式

从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素 op 次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果

从左至右,遇数压1,遇符弹2,再来计算。

例题

https://www.luogu.org/problem/P1449

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int a[1005],p,top,t;
char c;

int main()
{
    while(c=getchar())
    {
        if(c==@)
            break;
        if(isdigit(c)) t=t*10+c-0;
        if(c==.)
        {
            a[++top]=t;
            t=0;
        }
        if(c==+)
        {
            a[top-1]=a[top]+a[top-1];
            top--;
        }
        if(c==-)
        {
            a[top-1]=a[top-1]-a[top];
            top--;
        }
        if(c==*)
        {
            a[top-1]=a[top]*a[top-1];
            top--;
        }
        if(c==/)
        {
            a[top-1]=a[top-1]/a[top];
            top--;
        }
    }
    cout<<a[top];
    return 0;
}

注意事项:

1.有除法,并且就按c++里的整除运算

2.getchar()在cstdio里面

前缀,后缀表达式求值

原文:https://www.cnblogs.com/huaruoji/p/11702800.html

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