Basic Calculator II

来源:互联网 发布:csgo 电击枪 知乎 编辑:程序博客网 时间:2024/05/17 21:59

题目链接
这个题刚刚做过。是一个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();}
0 0
原创粉丝点击