博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
计算一个算数表达式的值
阅读量:4668 次
发布时间:2019-06-09

本文共 1531 字,大约阅读时间需要 5 分钟。

今天上数据结构,王老师讲的用栈实现算术表达式的值,晚上在实验室写了下,感觉自己的代码还是有问题(虽然还自己没有找到),感觉这个代码关于括号内运算符的优先级关系还是没有考虑好,这个代码也只是局限在10以内的加减乘除;先贴下代码,以后再来优化:

#include <iostream>

#include <stack>
#include <cstring>
#include <cstdio>
using namespace std;
stack<int> s2;
stack<int> s1;
char sign[4]={'+','-','*','/'};
char exp[110];
bool flag;
int cal(int a,int b,int c)
{
    if(c==0) return a+b;
    if(c==1) return a-b;
    if(c==2) return a*b;
    if(c==3) return a/b;
}
int solve()
{
    flag=0;
    int len=strlen(exp);
    exp[len]='#';
    len++;
    while(!s2.empty()) s2.pop();
    //s1.push(-1);
    int c=-1;
    for(int i=0;i<len;i++)
    {
        // cout<<exp[i]<<" ";
        if(s1.size()==0&&s2.size()==1&&i==len-1)
        {
            return s2.top();
        }
        if(exp[i]>='0'&&exp[i]<='9')
        {
            s2.push(exp[i]-'0');
        }
        else if(exp[i]=='(')
        {
            s1.push(4);
            flag=1;
        }
        else if(exp[i]==')'&&(c=s1.top())!=4)
        {
            s1.pop();
            int t1=s2.top();
            s2.pop();
            int t2=s2.top();
            s2.pop();
            int temp=cal(t2,t1,c);
           // cout<<temp<<"fgf ";
            s2.push(temp);
            i--;
        }
       else if(exp[i]==')'&&(c=s1.top())==4)
        {
            s1.pop();
            flag=0;
        }
        else
        {
            int j;
            if(!s1.empty()) c=s1.top();
            else c=-1;
            for(j=0;j<4;j++)
              if(exp[i]==sign[j])
                break;
             // cout<<j<<"  "<<exp[i]<<endl;
            if(flag&&j+5>c&&j<4) { s1.push(j);
              // cout<<c<<"  "<<j<<" df "<<exp[i]<<endl;
            }
            else if(!flag&&j>c&&j<4)
              s1.push(j);
            else
            {
            s1.pop();
            int t1=s2.top();
            s2.pop();
            int t2=s2.top();
            s2.pop();
            int temp=cal(t2,t1,c);
            s2.push(temp);
            //cout<<temp<<" fg ";
            i--;
            }
        }
    }
    return -1;
}
int main()
{
    while(scanf("%s",exp))
    {
        cout<<solve()<<endl;
    }
    return 0;
}

转载于:https://www.cnblogs.com/one--world--one--dream/archive/2011/10/11/2207781.html

你可能感兴趣的文章
二维数组中最大连通子数组
查看>>
java 正则表达式-忽略大小写与多行匹配
查看>>
mac 上亚马逊密钥登录
查看>>
css选择器中:first-child与:first-of-type的区别
查看>>
nopcommerce 二次开发
查看>>
NHibernate入门实例
查看>>
IBM_DS5020磁盘阵列做raid、热备并把盘阵挂在服务器上的步骤
查看>>
svg制作风车旋转
查看>>
《软件工程》课堂作业:返回一个整数数组中最大字数组的和
查看>>
ACM 美素数 (没AC)
查看>>
Sqlserver学习研究
查看>>
VTK图形模型主要对象
查看>>
c# Linq实现 获得某一个路径下所有文件的名(不含扩展名)
查看>>
动静态广播的区别
查看>>
前缀式计算(前缀表达式)
查看>>
Android手机通讯录解析
查看>>
汇编语言第一章
查看>>
centos 新建swap区文件
查看>>
Python
查看>>
UOJ 7 NOI2014 购票
查看>>