表达式求值

#pragma once
#include "stdafx.h"
#include "Stack.h"
//方法的声明实现的 分离写法 容易 报错,IDE还找不到错误的地方

//表达式求值
class Calculator {
private:
    //Calculator's stack,运算存储区
    Stack<double> s;
    //7个方法
public:
    //建立一个空计算器栈
    Calculator(void) {}
    //De建立一个空计算器栈
    virtual ~Calculator() {}
    //将一个double型操作数压入堆栈
    void Enter(double operand) {
        s.Push(operand);
    }
    //弹出2个操作数
    void GetTwoOperands(double &operand1, double &operand2) {
        if (s.IsEmpty()) {
            cerr << "No operand to be pop !" << endl;
            s.Clear();
            exit(1);
        }
        operand1 = s.Pop();
        if (s.IsEmpty) {
            cerr << "No operand to be pop !" << endl;
            s.Clear();
            exit(1);
        }
        operand2 = s.Pop();
    }
    //操作符运算
    void Compute(char op) {
        double operand1, operand2, result;
        GetTwoOperands(operand1, operand2);
        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.Clear();
                exit(1);
            } else
                result = operand1 / operand2; break;
            default:
                break;
        }
        s.Push(result);
    }
    //清空栈
    void Clear() {
        s.Clear();
    }
    //计算表达式的值
    void Run() {
        char op; //操作符
        double operand; //操作数
        cin >> op; //输入操作符
        while (op != '=') {
            switch (op) {
                case'+':case'-':case'*':case'/':
                    Compute(op); break; //运算
                default:cin.putback(op); //非操作符,回流
                    cin >> operand; //入操作数
                    Enter(operand); break; //入栈操作数
            }
            cin >> op; //输入操作符
        }
        cout << s.Pop() << endl;//最后出栈
        Clear();//清空栈
    }
};//!_class Calculator

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值