Basic Calculator II

本文介绍了一个使用C++实现的表达式求值程序。该程序利用栈来处理操作数和运算符,并通过自定义的优先级矩阵来决定运算顺序。文章提供了完整的源代码,并解释了如何读取输入字符串并计算其结果。

题目链接
这个题刚刚做过。是一个c++的实验课,所以我直接用别人的代码了
当然,博客上的代码是我自己的。

#include<iostream>
#include<stack>
#include<cctype>
using namespace std;

char priority[7][7]={
    {'<','<','<','<','>','>','>'},
    {'<','<','<','<','>','>','>'},
    {'>','>','<','<','>','>','>'},
    {'>','>','<','<','>','>','>'},
    {'>','>','>','>','>','=','>'},
    {'<','<','<','<','=','0','>'},
    {'<','<','<','<','>','<','='}
};

int detect(char temp)
{

    char oper[7]={'+','-','*','/','(',')','#'};
    for(int i=0;i<7;i++)
    {
        if(temp==oper[i])
        {
            return i;
        }
    }
    return 0;
}

char comp(char op1,char op2)
{
    int row=detect(op1);
    int col=detect(op2);
    return priority[row][col];

}




int caclu(int n1,int n2,char op)
{
    switch( op)
    {
    case '+':
        return n1+n2;
        break;
    case '-':
        return n1-n2;
        break;
    case '*':
        return n1*n2;
        break;
    case '/':
        if(n2==0)
        {
            cout<<"error // n2 is zero"<<endl;
            return 0;
        }
        int tempResult=n1/n2;
        return tempResult;
        break;
    }
    return 0;
}


int main()
{
    stack<int> intStack;
    stack<char> opStack;
    string input;

    cin>>input;

    opStack.push('#');
    int temp=0;
    int n=input.size();
    for(int i=0;i<n;i++)
    {
        if(isdigit(input[i]))
        {
            temp*=10;
            temp+=input[i]-'0';
            if(!isdigit(input[i+1]))
            {
                intStack.push(temp);
                temp=0;
            }

        }
        else
        {

            here:
            char compRes=comp(input[i],opStack.top());
            switch (compRes)
            {
            case '=':

                opStack.pop();
                break;
            case '<':
                {


                int tempN1=intStack.top();
                intStack.pop();

                int tempN2=intStack.top();
                char tempOp=opStack.top();
                opStack.pop();

                intStack.pop();
                int tempResult=caclu(tempN2,tempN1,tempOp);

                intStack.push(tempResult);
                goto here;
                break;
                }
            case '>':
                opStack.push(input[i]);
                break;

            }
        }

    }

    cout<<intStack.top();




}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值