蓝桥杯 表达式计算 【递归】

问题描述

  输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。

输入格式

  输入一行,包含一个表达式。

输出格式

  输出这个表达式的值。

样例输入

1-2+3*(4-5)

样例输出

-4

数据规模和约定

  表达式长度不超过100,表达式运算合法且运算过程都在int内进行。

解题思路

       这题和百练上的一个题几乎一模一样,唯一不同是白练上的那个题数据时double类型,看那个题懂了这个题也就懂了,链接:

https://blog.csdn.net/weixin_42765557/article/details/84453253

 

AC代码

#include <iostream>
using namespace std;
int expression_value();
int factor_value()
{
    int result=0;
    char op = cin.peek();
    if(op == '(') {
        cin.get();
        result = expression_value();
        cin.get();
    }
    else {
        while(op <= '9' && op >= '0') {
            cin.get();
            result = result*10 + (op - '0');
            op = cin.peek();
        }
    }
    return result;
}
int term_value()
{
    int result = factor_value();
    char op = cin.peek();
    while(op == '*' || op == '/') {
        if(op == '*') {
            cin.get();
            result *= factor_value();
        }
        else if(op == '/') {
            cin.get();
            result /= factor_value();
        }
        op = cin.peek();
    }
    return result;
}
int expression_value()
{
    int result = term_value();
    char op = cin.peek();
    while(op == '+' || op == '-') {
        if(op == '+') {
            cin.get();
            result += term_value();
        }
        else if(op == '-') {
            cin.get();
            result -= term_value();
        }
        op = cin.peek();
    }
    return result;
}
int main()
{
    cout << expression_value();
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值