需求
编写程序计算诸如 (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;
}
测试结果