C++实现简易计算器

1.原理:利用栈的原理,将表达式转化为后缀表达式然后计算

2.代码:

#include
#include
#include
#include
using namespace std;
template 
class Stack{
private :
     T data[1000];
     int t;
public :
     Stack(){t=0;}
     void clear(){t=0;}
     T pop(){
       if (t<=0) {
            cout<<"stack is empty"<=1000){
        cout<<"the stack is full"<infixExp= infixExp;
        if (infix_to_postfix()){
            return ans=cal_postfix();
        }else{
           cout<<"语法错误,请检查表达式"<>r;
     int i;
     for (i=r.length()-1;i>=0;i--)
        if(r[i]!='0') break;
     if (r[i]=='.') i--;
     return  r.assign(r,0,i+1);
}
double Calculator::cal(double num1,double num2,char op)
{
    switch(op){
  case '+':
      return num1+num2;
  case '-':
      return num1-num2;
  case '*':
      return num1*num2;
  case '/':
      return num1/num2;
  default:
     return 0.0;
    }
}

int Calculator::get_priority(char c){
    switch(c){
      case '+':case '-': return 1;
      case '*':case '/': return 2;
      case '(':return 0;
      case ')':return 0;
      case '#':return -2;
      default:
        return -1;
    }
}
bool Calculator::infix_to_postfix()
{
    Stack stk;
    int a_num_end=0,is_negative=0;
    string result="#";
    stk.push('#');
    for (int i=0;i='0')||c=='.') {
                if(a_num_end&&!is_negative) {result+='#'; }
                is_negative=0;
                result+=c;
                a_num_end=0;
        }
        else{a_num_end=1;
         if(c=='(') stk.push('(');
        else if (c==')') {
                while (stk.top()!='(')
                {
                    result+='#';
                    result+=stk.pop();
                }
                stk.pop();
            }
        else {
             int p = get_priority(c);
             if (p==-1) return false;
             while (p<=get_priority(stk.top())){
                result+='#';
                result+=stk.pop();
             }
             stk.push(c);
        }
        }
    }
    while (stk.top()!='#'){
        result+='#';
        result+=stk.pop();
    }
    result+='#';
    cout< stk1;
    for (int i=1;i='0'&&c<='9')) stk1.push(read_num(postfixExp,&i));
        else {
           double y  = stk1.pop();
           double x = stk1.pop();
           stk1.push(cal(x,y,c));
        }
    }
   return stk1.pop();
}
int main()
{
    Calculator c;
    string ini;
  while (1){
        cout<<"输入要计算的表达式(以字母Q结束程序):"<>ini;
        if(ini.length()==1&&ini[0]=='Q') break;
        c.calculate(ini);
        c.display();
    }
    //c.calculate("(-5)*10+20/20-2*3*6/36");
    //c.display();
    return 0;
}


你可能感兴趣的:(C++实现简易计算器)