pipi 1362(表达式求值)

这段代码实现了一个C++程序,用于解析并计算中缀表达式。它使用栈来处理运算符和数字,遵循运算符优先级进行计算。程序能够处理加减乘除四种基本运算,并将输入的字符串转换为数值进行计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int mod=1e9+7;
const int N=1e5+10;
int priori(char c)//判断一个字符的优先级,返回的是它的优先级
{
    if(c=='*'||c=='/')
        return 2;
    if(c=='+'||c=='-')
        return 1;
}
int iswhatandcompute(char c,int n1, int n2)
{
    /*
    c:操作符
    n1,n2:操作数
    返回的是n2 c n1 的值
    */
    if (c=='*')
        return n1*n2;
    if(c=='/')
        return n2/n1;
    if(c=='+')
        return n2+n1;
    if(c=='-')
        return n2-n1;
}
int chartoint(char c)
{
    //字符转数字
    return c-48;
}
int isoperate(char c)
{
    /*
    判断字符是数字还是操作符
    操作符:返回1
    数字:返回0
    */
    if(c=='+'||c=='-'||c=='*'||c=='/')
        return 1;
    else
        return 0;
}
void compute(string s)
{
    stack<char> op;
    stack<int> num;
    int n=0;
    //计算表达式的值
    int i;
    int size_s=s.size();
    for(i=0; i<size_s;)
    {
        if (isoperate(s[i])) //判断s[i]是操作符
        {
            num.push(n);
            n=0;
            if(!op.empty()) //操作符栈非空
            {
                char temp=op.top();
                while(!op.empty()&&priori(op.top())>=priori(s[i]))
                {
                    temp=op.top();
                    int n1=num.top();
                    num.pop();
                    int n2=num.top();
                    num.pop();
                    int n3=iswhatandcompute(temp,n1,n2);
                    num.push(n3);
                    op.pop();
                }
                op.push(s[i]);
                i++;

            }
            else
            {
                op.push(s[i]);
                i++;
            }
        }
        else //是数字
        {
            n=n*10+chartoint(s[i]);
            i++;
        }
    }
    num.push(n);

    while(!op.empty())
    {
        char t=op.top();
        op.pop();
        int t1=num.top();
        num.pop();
        int t2=num.top();
        num.pop();
        int t3=iswhatandcompute(t,t1,t2);
        num.push(t3);
    }
    int k=num.top();
    cout<<k<<endl;
}

int main()
{
    string str;
    while(cin>>str)
    {
        compute(str);
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值