栈的简单应用—表达式求值(即简单计算器)

写在前面——

阅读了学长的代码过后,我深深的感到了我的孤陋寡闻。出于对unordered_map这个工具的不熟练,我粗浅的进行了一个复现,用的是比较中规中矩的类的办法。(所以理论上python实现也是可能的)

1.理论准备

为了准确的确定运算顺序,需要建立两个栈,即操作数栈(ODS),操作符栈(OPS)。然后进行扫描,每次遇到操作数栈时,便入栈;遇到操作符栈时,连续弹出两个操作数来执行运算,然后把结果压入栈顶。

2.理论转化

建立一个计算器类,内嵌一个栈类,作为操作数栈。成员函数至少包括:操作数压入栈,连续两个弹出数栈,执行运算,输入,运算过程控制。

代码实现(由于篇幅过长,加之我又太菜,这里仅展现核心的几个函数)

1.定义类

class jisuanqi{
	private:
		stack<double>s;//操作数栈 
		void enter(double num);//操作数压入栈 
		bool gettwonum(double &o1,double &o2);//连续两个压入栈 
		void computer(char op);//指定运算
	public:
	    void run();//运行
	#	void clear();//清空 ,也可以不要吧,看题目要求 
};

2.压入数函数


void jisuanqi::enter(double num)
{
	s.push(num);
 } 

3.两个数与栈的操作以及判别

bool jisuanqi::gettwonum(double &o1,double &o2)
{
	if(s.isEmpty())
	{
		cerr<<"搞错了!"<<endl;
		return false; 
	}
	o1=s.pop();
	if(s.isEmpty())
	{
		cerr<<"又错啦!"<<endl; 
		return false;
	}
	o2=s.pop();
	return true;
}

3.运算函数(核心!!!)

    

void jisuanqi::compute(char op)
{
	double o1,o2;
	bool result=gettwonum(o1,o2);
	if(result)
	{
		switch(op)
		{
			case'+':
				s.push(o1+o2);
			case'-':
				s.push(o2-o1);
			case'*':
				s.push(o2*o1);
			case'/':
				if(o1==0)
				{
					cerr<<"除数可不能为0哦!"<<endl;
					#s.clear();//可要可不要 
				}
				else
				{
					s.push(o2/o1);
				}
			case'^':
				s.push(pow(o2,o1));
			default:
				cerr<<"错啦,!"<<endl;
		}
		cout<<"="<<s.peek()<<" ";
	}
	else
	{
		#s.clear(); //可要可不要 
	}
}

4.一些辅助函数

  01.字符串转化函数



inline double strin(const string &str)
{
	istringstream stream(str);
	double result;
	stream>>result;
	return result;
 } 

02.clear()函数

   

void jisuanqi::clear(){
	s.clear();
}

              ————————————华丽的分界线——————————

                                     这里附上大佬的代码,供大家膜拜

//202031061018 刘知鑫
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <unordered_map>

using namespace std;

stack<int> num;
stack<char> op;

void eval()
{
    auto b = num.top();
    num.pop();
    auto a = num.top();
    num.pop();
    auto c = op.top();
    op.pop();
    int x;
    if (c == '+') x = a + b;
    else if (c == '-') x = a - b;
    else if (c == '*') x = a * b;
    else x = a / b;
    num.push(x);
}

int main()
{
    unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
    string str;
    cin >> str;
    for (int i = 0; i < str.size(); i ++ )
    {
        auto c = str[i];
        if (isdigit(c))
        {
            int x = 0, j = i;
            while (j < str.size() && isdigit(str[j]))
                x = x * 10 + str[j ++ ] - '0';
            i = j - 1;
            num.push(x);
        }
        else if (c == '(') op.push(c);
        else if (c == ')')
        {
            while (op.top() != '(') eval();
            op.pop();
        }
        else
        {
            while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) eval();
            op.push(c);
        }
    }
    while (op.size()) eval();
    cout << num.top() << endl;
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值