百练4132 四则运算表达式求值

要是学过编译原理这题就比较好写了,但是不好想到。

简单算术表达式的上下文无关文法为:

exp--> exp addop term | term

addop--> + | -

term--> term mulop factor | factor

mulop--> * | /

factor --> (exp) | number

将文法化成EBNF范式,然后采用递归下降的方式求解exp的值:

cin.peek()函数看输入流中的下一个字符,但是不取走,真的好用。

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<iomanip>
using namespace std;
double factor();
double term();
double exp();

double exp()   //求表达式的值
{
    double res=term();
    while(true)
    {
        char op = cin.peek(); //看输入流中的下一个字符,不取走
        if(op=='+' || op=='-')
        {
            cin.get();  //从输入流中取走一个字符
            double val = term();
            if(op=='+') res+=val;
            else res-=val;
        }else break;
    }
    return res;
}

double term()
{
    double res=factor();
    while(true)
    {
        char op = cin.peek();
        if(op=='*' || op=='/')
        {
            cin.get();
            double val = factor();
            if(op=='*') res *= val;
            else res /=val;
        }else break;
    }
    return res;
}

double factor()
{
    char c = cin.peek();
    double res=0;
    if(c=='(')
    {
        cin.get();
        res = exp();
        cin.get();
    }else{
        while(isdigit(c))
        {
            cin.get();
            res = res*10+c-'0';
            c=cin.peek();
        }
        if(c=='.')  //有小数部分
        {
            double val=0;
            double base = 0.1;
            cin.get();
            c=cin.peek();
            while(isdigit(c))
            {
                cin.get();
                val += (c-'0')*base;
                c=cin.peek();
                base = base * 0.1;
            }
            res += val;
        }
    }
    return res;
}


int main()
{
    double ans = exp();
    cout<<fixed<<setprecision(2)<<ans<<endl;
    return 0;

}






  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值