/* calculator.h */
#ifndef __calculator_h__
#define __calculator_h__
#include <iostream.h>
#include "stack.h"
class calculator {
private:
//存放操作数的栈
stack<double> s;
//将一个double型操作数压入栈中
void enter(double operand) {
s.push(operand);
}
//从栈顶读取两个操作数
int gettwooperands(double &operand1, double &operand2)
{
if (s.stackempty()) {
cerr << "no operand to pop!" << endl;
s.clearstack();
return 0;
}
operand1 = s.pop();
if (s.stackempty()) {
cerr << "no operand to pop!" << endl;
s.clearstack();
return 0;
}
operand2 = s.pop();
return 1;
}
//将调用gettwooperands读取的两个操作数做运算op
void compute(char op)
{
double operand1, operand2, result;
if (!gettwooperands(operand1, operand2)) return;
switch(op) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
case '*': result = operand1 * operand2; break;
case '/':
if (operand2 == 0) {
cerr << "divided by 0!" << endl;
s.clearstack();
return;
}
else result = operand1 / operand2;
break;
}
s.push(result);
}
//清空操作数栈
void clear() { s.clearstack(); }
public:
//构造函数,建立一空栈
calculator(void) {}
//计算表达式的值
void run() {
char op;
double operand;
while (1) {
cin >> op;
if (cin.eof()) return;
while (op != '=') {
switch(op) {
case '+': case '-': case '*': case '/':
compute(op);
break;
default:
cin.putback(op);