输入为四则运算表达式,仅由数字、+、-、*、/、(、)组成,没有空格,要求求其值。假设运算符结果都是整数。“/”结果也是整数。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int expression_value();//读入表达式,返回其值
int factor_value();//读入一个因子,并且返回其值
int term_value();//读入一项,返回其值
int main(){
cout<<expression_value()<<endl;
return 0;
}
int expression_value(){//求一个表达式的值
int result=term_value();//求第一项的值
bool more=true;//有没有新的项
while(more){
char op=cin.peek();//看一个字符,不取走。cin会从输入流里面拿走
if(op=='+'||op=='-'){
cin.get();
int value=term_value();
if(op=='+')
result+=value;
else result-=value;
}
else more=false;//如果是右括号,说明输入流结束。
}
return result;
}
int term_value(){//求一个项的值
int result=factor_value();
while(true){
char op=cin.peek();
if(op=='*'||op=='/'){//如果有乘除,说明还有后续因子
cin.get();//从输入中取走一个字符