关于后缀表达式
  • 板块学术版
  • 楼主Asher12
  • 当前回复15
  • 已保存回复15
  • 发布时间2023/8/3 21:43
  • 上次更新2023/11/3 06:03:31
查看原帖
关于后缀表达式
836643
Asher12楼主2023/8/3 21:43

用栈写了一个处理后缀表达式的程序,但是得数错误。望神犇指教!

#include <iostream>
#include <cctype>
#include <string>
#include <stdexcept>
using namespace std;
struct stack
{
    int stk[100010];
    int t=0;
    void push(int x)
    {
        stk[t]=x;
        ++t;
    }
    bool empty()
    {
        if (t==0)
        {
            return true;
        }
        return false;
    }
    int pop()
    {
        int kkk=-32767;
        try
        {
            if (empty()==true)
            {
                throw runtime_error("Runtime Error:Try to \"pop\" the top element of stack when the stack is empty.");
            }
            else
            {
                kkk=stk[t-1];
                --t;
            }
        }
        catch (runtime_error err)
        {
            cerr<<err.what()<<'\n';
        }
        return kkk;
    }
    int top()
    {
    	int kkk=-32767;
        try
        {
            if (empty()==true)
            {
                throw runtime_error("Runtime Error:Try to access the top element of stack when the stack is empty.");
            }
            else
            {
                kkk=stk[t-1];
            }
        }
        catch (runtime_error err)
        {
            cerr<<err.what()<<'\n';
        }
        return kkk;
    }
    int size()
    {
        return t;
    }
};
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	string str;
	stack stk;
	getline(cin,str);
	int v=0;
	bool flag=false;
	for (auto i:str)
	{
		if (flag==true&&i==' ')
		{
			stk.push(v/10);
			v=0;
			flag=false;
			continue;
		}
		if (isdigit(i))
		{
			flag=true;
			v+=(static_cast<int>(i-'0'))*10;
		}
		else if (i=='+'||i=='-'||i=='*'||i=='/')
		{
			int a=stk.top();
			stk.pop();
			int b=stk.top();
			stk.pop();
			int ans=0;
			switch (i)
			{
				case '+':
						ans=b+a;
						break;
				case '-':
						ans=b-a;
						break;
				case '*':
						ans=b*a;
						break;
				case '/':
						ans=b/a;
						break;
			}
			stk.push(ans);
		}
	}
	cout<<stk.top()<<'\n';
	stk.pop();
	try
	{
		if (stk.empty()==false)
		{
			throw logic_error("Error!\n");
		}
	}
	catch (logic_error err)
	{
		cout<<err.what();
		return -1;
	}
	return 0;
}

//9 3 1 - 3 * + 10 2 / +
2023/8/3 21:43
加载中...