栈——表达式求值

老师代码

//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;
}

我的代码

#include<stdio.h>    
#include<string.h>    
#include<math.h>    
#define MAX 10000000    
  
int fig[100];  
char sym[100];  
int temp1 = -1, temp2 = -1;  
char op[9] = {'+','-','*','/','(',')','#','^','%'};  
char checklist[9][9] =   
{  
    {'>','>','<','<','<','>','>','<','<'},  
    {'>','>','<','<','<','>','>','<','<'},  
    {'>','>','>','>','<','>','>','<','>'},  
    {'>','>','>','>','<','>','>','<','>'},  
    {'<','<','<','<','<','=',' ','<','<'},  
    {'>','>','>','>',' ','>','>','>','>'},  
    {'<','<','<','<','<',' ','=','<','<'},  
    {'>','>','>','>','<','>','>','<','>'},  
    {'>','>','>','>','<','>','>','<','>'}  
};  

int number(char* q)  
{  
    return (int)(*q-'0');  
}  
  
void push_figure(int q)  
{  
    fig[++temp1]=q;  
}  
  
int pop_figure()   
{  
    return fig[temp1--];  
}  
  
char pop_symbol()   
{  
    return sym[temp2--];  
}  
  
void push_symbol(char ch)   
{  
    sym[++temp2]=ch;  
}  
  
int operate(int x, int y, char symbol)   
{  
    switch (symbol)   
    {  
    case '+': return x+y;  
    case '-': return x-y;  
    case '*': return x*y;  
    case '/':   
            if(y) return x / y;  
            else   
            {  
            printf("Divide 0.\n");  
            return MAX;  
            }  
    case '%': return (int)fmod(x,y);  
    case '^':   
            if (y >= 0) return (int)pow(x,y);  
            else   
            {  
            printf("error.\n");  
            return MAX;  
            }     
    default: printf("error.\n");  
          
        return MAX;  
    }  
}  
  
char compare(char x,char y)   
{  
    int a, b;  
    for(int i = 0; i <= 8; i++)   
    {  
        if(op[i] == x)   
        {  
            a = i;  
            break;  
        }  
    }  
      
    for(int i = 0; i <= 8; i++)   
    {  
        if(op[i] == y)   
        {  
            b = i;  
            break;  
        }  
    }  
    return checklist[a][b];  
}  
int main()   
{  
    int n,flag = 0;    
    char expression[100], * p;  
    scanf("%d", &n);  
      
    while(n--)   
    {     
        flag = 2;  
        scanf("%s", expression);  
        strcat(expression,"#");   
          
        p = expression;  
        push_symbol('#');  
  
    k:while(*p != '#' || sym[temp2] != '#')   
    {  
        if(*p >= '0' && *p <= '9')   
        {  
            if(flag == 0)   
            {  
                push_figure(pop_figure() * 10 + number(p++));  
                flag = 0;  
            }  
              
            else  
                push_figure(number(p++));  
            flag = 0;  
        }  
          
        else   
        {  
            if(flag == 1)   
            {  
                if(*p == '+' || *p == '-' || *p == '*' || *p == '/' || *p == '%' || *p == '^')   
                {  
                    printf("error.\n");  
                    goto j;  
                }  
            }  
            
            if(*p == '(') flag = 1;  
            else flag = 2;  
  
            if (temp2 == -1)   
            {  
                printf("error.\n");  
                goto j;  
            }  
            else   
            {  
                char ch = pop_symbol(), ans;  
                ans = compare(ch, *p);  
                if(ans == ' ')  
                {  
                    printf("error.\n");  
                    goto j;  
                }  
                  
                else if(ans == '<')   
                {  
                    push_symbol(ch);  
                    push_symbol(*p++);  
                    goto k;  
                }  
                  
                else if(ans == '=')   
                {  
                    p++;  
                    goto k;  
                }  
              
                else   
                {  
                    int integer_x, integer_y;  
                    integer_y = pop_figure();  
                    integer_x = pop_figure();  
                      
                    int judge = operate(integer_x, integer_y, ch);  
                    if (judge == MAX) goto j;  
                  
                    else  
                        push_figure(judge);  
                    continue;  
                }  
                p++;  
            }  
        }  
    }  
    if(temp1 == 0 && temp2 == 0) printf("%d\n", fig[temp1]);  
      
    else   
    {  
        printf("error.\n");  
    }  
  
    j:  memset(expression,'\0',100);  
  
    temp1 = -1;  
    temp2 = -1;  
    }  
    return 0;  
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一、问题描述 在控制台下实现一个对算术表达式求值的模拟程序。 二、基本要求 该演示程序具有如下基本功能: (1) 表达式输入,以字符序列的形式从终端输入一个语法正确的数值表达式(float型),且表达式中只含有+、-、*、/、( 、)6 种运算符,输入格式如下: <变量><运算符><变量>……<回车> 例如表达式: 100+(15/3)*2 输入格式为: 100+(15/3)*2<回车> 注意: 输入的表达式中间不含空格。 (2) 表达式结果的输出,输出形式为: <表达式> = <结果> 例如表达式: 100+(15/3)*2 输出形式为: 100+(15/3)*2 = 110 注意: 此处的输出结果为整个表达式的数值结果。 (3) 数据合法性检验 主要是针对原表达式中除数为 0 的情况。 三、界面效果 表达式求值模拟程序 功能菜单: ============== [1] 输入表达式并求值 [0] 退出 ============== 请输入你的选择 (0~1):1 请输入一个表达式 : 100+(15/3)*2 计算结果如下: 100+(15/3)*2 = 110 请输入你的选择 (0~1):0 四、测试数据 (1) 8 = (2) 1+2+3+4 = (3) 88-1*5 = (4) 1024/4*8 = (5) 1024/(4*8) = (6) (20+2)*(6/2) = (7) 3-3-3 = (8) 80/(9-9) = (9) (6+2*(3+6*(6+6)) = (10) (((6+6)*6+3)*2+6)*2 = 五、实现提示 (1) 设置运算符和操作数辅助分析算符优先关系; (2) 在读入字符序列时,完成运算符和操作数的处理,以及相应运算; (3) 在识别处运算数的同时,要将其字符序列形式转化成 float 型数据形式; (4) 输入的字符序列中,操作数不一定是一位数,可能是多位数,如 16+32 ; (5) 使用 Lab3-1 实现的的 ADT 基本操作完成本次作业 ; (6) 在程序中会用到两类:操作数和运算符,分别为 float 型数据和字符型数据, 思考在同一个程序中如何处理两类不同的数据类型? (7) 算符之间的优先关系参考课本 P53 页表 3.1 。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值