#include <iostream>
#include "seqStack.h"
using namespace std;
class Calculator //模拟一个简单的计算器。此计算器对键盘读入的后缀表达式求值
{
public:
Calculator(); //构造函数
void Run(); //执行表达式计算
void Clear(); //将栈清空
private:
void AddOperand(double value); //操作数进栈
bool Get2Operands(double &left,double &right);//从栈中出栈两个操作数,&为引用
void DoOperator(char op); //形成运算指令,进行计算
seqStack s;
};
Calculator::Calculator()
{
s.InitseqStack();
}
void Calculator::AddOperand(double value)
{
s.Push(value);
}
bool Calculator::Get2Operands(double &left,double &right)
{
if (s.isEmpty())
{
cout<<"操作数不存在"<<endl;
return false;
}
right=s.Pop();
if (s.isEmpty())
{
cout<<"操作数不存在"<<endl;
return false;
}
left=s.Pop();
return true;
}
void Calculator::DoOperator(char op)
{
double left,right;
if (Get2Operands(left,right))
{
switch(op)
{
case '+':
s.Push(left+right); break;
case '-':
s.Push(left-right); break;
case '*':
s.Push(left*right); break;
case '/':
if(right==0.0)
{
cout<<"用0做除数,错误!"<<endl;
Clear(); //若除0,则报错,清栈
}else s.Push(left/right);
break;
}
} else Clear();//取操作数出错,清栈
}
void Calculator::Run()
{
char ch;
double newoperand;
cout<<"请输入后缀表达式,以=结尾"<<endl;
while (cin>>ch,ch!='=')
{
switch(ch){
case '+':
case '-':
case '*':
case '/':
DoOperator(ch);
break;
default:
cin.putback(ch); //将字符放回输入流,以便能用流操作符将其按一个浮点操作数重新读入
cin>>newoperand; //重新读操作数
AddOperand(newoperand);//将操作数入栈
break;
}
}
cout<<""<<s.GetTop()<<endl;
}
void Calculator::Clear()
{
s.InitseqStack();
}
/*
void main()
{
Calculator c;
c.Run();
};
*/
#include "seqStack.h"
using namespace std;
class Calculator //模拟一个简单的计算器。此计算器对键盘读入的后缀表达式求值
{
public:
Calculator(); //构造函数
void Run(); //执行表达式计算
void Clear(); //将栈清空
private:
void AddOperand(double value); //操作数进栈
bool Get2Operands(double &left,double &right);//从栈中出栈两个操作数,&为引用
void DoOperator(char op); //形成运算指令,进行计算
seqStack s;
};
Calculator::Calculator()
{
s.InitseqStack();
}
void Calculator::AddOperand(double value)
{
s.Push(value);
}
bool Calculator::Get2Operands(double &left,double &right)
{
if (s.isEmpty())
{
cout<<"操作数不存在"<<endl;
return false;
}
right=s.Pop();
if (s.isEmpty())
{
cout<<"操作数不存在"<<endl;
return false;
}
left=s.Pop();
return true;
}
void Calculator::DoOperator(char op)
{
double left,right;
if (Get2Operands(left,right))
{
switch(op)
{
case '+':
s.Push(left+right); break;
case '-':
s.Push(left-right); break;
case '*':
s.Push(left*right); break;
case '/':
if(right==0.0)
{
cout<<"用0做除数,错误!"<<endl;
Clear(); //若除0,则报错,清栈
}else s.Push(left/right);
break;
}
} else Clear();//取操作数出错,清栈
}
void Calculator::Run()
{
char ch;
double newoperand;
cout<<"请输入后缀表达式,以=结尾"<<endl;
while (cin>>ch,ch!='=')
{
switch(ch){
case '+':
case '-':
case '*':
case '/':
DoOperator(ch);
break;
default:
cin.putback(ch); //将字符放回输入流,以便能用流操作符将其按一个浮点操作数重新读入
cin>>newoperand; //重新读操作数
AddOperand(newoperand);//将操作数入栈
break;
}
}
cout<<""<<s.GetTop()<<endl;
}
void Calculator::Clear()
{
s.InitseqStack();
}
/*
void main()
{
Calculator c;
c.Run();
};
*/