递归方法计算一个中缀表达式的值

来源:互联网 发布:单片机助手 编辑:程序博客网 时间:2024/06/06 07:30

需求

编写程序计算诸如 (7+2)/3-5*2+12*(4+3) 这种表达式的值。

分析

将表达式中情况分解成三类

  • 因子 factor 包括 单个数字或者括号内表达式,优先度1
  • 项 term 对于*/类型的计算,符号左右两侧称为项,优先度2
  • 表达式 对于+-类型的计算,符号左右两侧称为表达式,优先度3

代码

#include <iostream>#include <cstring>#include <cstdlib>using namespace std;//因子 由表达式或数字构成int factorValue();//项 由因子及*/构成int termValue();//表达式 由项及+-构成int expressionValue();int main(){    cout << expressionValue() << endl;    return 0;}int factorValue(){    int result = 0;    char c = cin.peek();    if(c == '(') {        cin.get();        result = expressionValue();        cin.get();    } else {        while(isdigit(c)) {            result = result * 10 + c - '0';            cin.get();            c = cin.peek();        }    }    return result;}int termValue(){    int result = factorValue();    bool more = true;    while(more) {        char op = cin.peek();        if(op == '*' || op == '/') {            cin.get();            int value = factorValue();            if(op == '*')                result *= value;            else                result /= value;        } else            more = false;    }    return result;}int expressionValue(){    int result = termValue();    bool more = true;    while(more) {        char op = cin.peek(); //看之后的第一项        if(op == '+' || op == '-') {            cin.get();            int value = termValue();            if(op == '+')                result += value;            else                result -= value;        } else            more = false;    }    return result;}

测试结果

这里写图片描述

原创粉丝点击