程序要求:
输入一个类似2 + 3 * ( 4 + 5 ) – 6/ 4的数学表达式,前提是输入的表达式是正确的,然后计算输出结果(本程序没考虑括号的匹配问题以及除数为0产生的异常)
#include <iostream>
#include <cstring>
#include <cctype>
#include <stack>
void evaluate(stack<int>& numbers,stack<char>& operations);
int input(istream& ins);
int main()
{
cout<<"Input"<<endl;
int result=0;
result=input(cin);
cout<<result<<endl;
cout<<"End"<<endl;
return 0;
}
int input(istream& ins){
stack<int> numbers;
stack<char> operations;
int number;
char symbol;
while(ins && ins.peek()!='\n')
{
if(isdigit(ins.peek()))
{
ins>>number;
numbers.push(number);
}
else if(strchr("*/(",ins.peek())!=NULL)
{
ins>>symbol;
operations.push(symbol);
}
else if(ins.peek()==')')
{
ins.ignore();
while(operations.top()!='('){
evaluate(numbers,operations);
}
operations.pop();
}
else if(strchr("+-",ins.peek())!=NULL)
{
while(!operations.empty() && operations.top()!='(')
{
evaluate(numbers,operations);
}
ins>>symbol;
operations.push(symbol);
}
}
while(!operations.empty()){
evaluate(numbers,operations);
}
return numbers.top();
}
void evaluate(stack<int>& numbers,stack<char>& operations){
int operand1,operand2;
operand2=numbers.top();
numbers.pop();
operand1=numbers.top();
numbers.pop();
switch(operations.top())
{
case '+':
numbers.push(operand1+operand2);
break;
case '-':
numbers.push(operand1-operand2);
break;
case '*':
numbers.push(operand1*operand2);
break;
case '/':
numbers.push(operand1/operand2);
break;
}
operations.pop();
}