简单计算器

来源:互联网 发布:对方qq网络状态准确吗 编辑:程序博客网 时间:2024/06/18 04:02
链接
#include<bits/stdc++.h>using namespace std;stack<int> num;stack<char> ope;int oppe(int num1,int num2,char op){    if(op=='+') return num1+num2;    if(op=='-') return num1-num2;    if(op=='*') return num1*num2;    if(op=='/') return num1/num2;    return 0;}void calculate(string str){    int len = str.length();    while(!num.empty()) num.pop();    while(!ope.empty()) ope.pop();    for(int i=0;i<len;i++){        if(str[i]>='0'&& str[i]<='9'){            int tmp = 0;            while(str[i]>='0'&&str[i]<='9'&&i<len){                tmp = tmp*10 + str[i++]-'0';            }            num.push(tmp);            i--;        }else{            if(str[i]==')'){                while(ope.top()!='('){                    int num2 = num.top(); num.pop();                    int num1 = num.top(); num.pop();                    num.push(oppe(num1,num2,ope.top()));                    ope.pop();                }                if(!ope.empty()) ope.pop();            }            else if(str[i]=='(') ope.push(str[i]);            else if(str[i]=='+'||str[i]=='-'){//考虑优先级,如果该字符是+、-则前一运算符可以计算,并将此运算符放入栈中,前面的均计算                while(!ope.empty()&&ope.top()!='('){                    int num2 = num.top(); num.pop();                    int num1 = num.top(); num.pop();                    num.push(oppe(num1,num2,ope.top()));                    ope.pop();                }                ope.push(str[i]);            }            else{                while(!ope.empty() &&  ope.top() == '*' && ope.top() == '/' ){                    int num2 = num.top(); num.pop();                    int num1 = num.top(); num.pop();                    num.push(oppe(num1,num2,ope.top()));                    ope.pop();                }              ope.push(str[i]);            }        }    }    while(!ope.empty()){        int num2 = num.top(); num.pop();        int num1 = num.top(); num.pop();        num.push(oppe(num1,num2,ope.top()));        ope.pop();    }    cout << num.top()<<endl;}int main(){    string str;    cin >> str ;    calculate(str);return 0;}

原创粉丝点击