//Calculator.cpp
#include "Calculator.h"
void Calculator::Enter(double num)
//住栈中存放数据值
{
s.Push(num);
}
//从栈中取得操作数并赋值给形参,若操作数不够,则打印出错信息,并返回False
Boolean Calculator::GetTwoOperands(double& opnd1,double& opnd2)
{
if(s.StackEmpty())
//检查操作数是否存在
{
cerr<<"Missing operand!"<<endl;
return False;
}
opnd1=s.Pop();
//取右操作数
if(s.StackEmpty())
{
cerr<<"Missing operand!"<<endl;
return False;
}
opnd2=s.Pop();
//取左操作数
return True;
}
void Calculator::Compute(char op)
{
Boolean result;
double operand1,operand2;
//取两个操作数,并判断是否成功取到
result=GetTwoOperands(operand1,operand2);
if(result==True)
switch(op)
{
case '+':
s.Push(operand2+operand1);
break;
case '-':
s.Push(operand2-operand1);
break;
case '*':
s.Push(operand2*operand1);
break;
case '/':
if(operand1==0.0)
{
cerr<<"Divide by 0!"<<endl;
s.ClearStack();
}
else
s.Push(operand2/operand1);
break;
case '^':
s.Push(pow(operand2,operand1));
break;
}
else
s.ClearStack();
//出错!清空计算器
}
void Calculator::Run()
{
char c;
double newoperand;
while(cin>>c&&c!='=')
//读入字符,直到遇“=”时退出
{
switch(c)
{
case '+':
case '-':
case '*':
case '/':
case '^':
Compute(c);
//读到运算符,求值
break;
default:
//非运算符,则必为操作数,将数字送回
cin.putback(c);
//读入操作符并将其存入栈中
cin>>newoperand;
Enter(newoperand);
break;
}
}
//答案已在栈顶,用peek输出之
if(!s.StackEmpty())
cout<<s.Peek()<<endl;
}
//清空操作数栈
void Calculator::Clear()
{
s.ClearStack();
}