利用栈实现简单计算器的例子(Calculator)

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

/* 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);

cin >> operand;

Enter(operand);

break;

}

cin >> op;

if (cin.eof()) return;

}

cout << s.Pop() << endl;

Clear();

}

}

};

#endif

//////////////////////////////////////////////////////////////////

// Calc.cpp

#include "calc.h"

void main()

{

Calculator c;

c.Run();

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航