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

xiaoxiao2021-02-28  51

需求

编写程序计算诸如 (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; }

测试结果

转载请注明原文地址: https://www.6miu.com/read-52424.html

最新回复(0)