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

[入库:2005年8月19日] [更新:2007年3月24日]

本文简介:选择自 yangjq 的 blog

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

本文关键:利用栈实现简单计算器的例子(Calculator)
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top