编程语言

img YangJq

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

发表于2004/10/25 0:10:00  1546人阅读

分类: 数据结构2004

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

阅读全文
0 0

相关文章推荐

img
取 消
img