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

版权声明:记笔记~~~ https://blog.csdn.net/weixin_42765557/article/details/87925524

问题描述

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

输入格式

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

输出格式

  输出这个表达式的值。

样例输入

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;
}

猜你喜欢

转载自blog.csdn.net/weixin_42765557/article/details/87925524
今日推荐