晚上七点到八点花了不到一个小时写出来的表达式求值程序,因为几个无语的错误,居然调试到现在,累计调试的时间大概有五个小时了吧,太打击自信了!

教训:写代码细心,实时检验,以免程序长了之后花数倍的时间调试

#include<stack>
//#include<string>
#include<iostream>

using namespace std;


short Com[7][7]={ {1,1,0,0,0,1,1},{1,1,0,0,0,1,1},//运算符优先级
    {1,1,1,1,0,1,1},{1,1,1,1,0,1,1},
    {0,0,0,0,0,2,1},{1,1,1,1,1,1,1},{0,0,0,0,0,0,0}};
   
int Operate(int a,char theta,int b)//计算
{
if(theta=='+')return a+b;
if(theta=='-')return a-b;
if(theta=='*')return a*b;
if(theta=='/')return a/b;
}
int StoN(char z)//返回操作符代号便于计算优先级
{ if(z=='+')return 0;
if(z=='-')return 1;
if(z=='*')return 2;
if(z=='/')return 3;
if(z=='(')return 4;
if(z==')')return 5;
if(z=='#')return 6;
}

int count(char s[])//主程序
{
stack<char> oper;
stack<int> num;
int aa,bb,cc,t,ccc;
oper.push('#');
int l=strlen(s),i,j;
char temp[]="#";
strcat(s,temp);
//s[l+1]=35;
char c,theta;
i=-1;
c=s[++i];
while(c!='#' || oper.top()!='#')//oper.top()!='#'
{
   //if(!(c=='+' || c=='-' || c=='*' || c=='/' || c=='(' || c==')'))
   if(c>='0' && c<='9')
   {
    t=0;
    while(c>='0'&&c<='9')
    {
     t++;
     c=s[++i];
    }
    int d=atoi(s+i-t);
    i--;
    num.push(d);
    c=s[++i];
   }
   else
   {
    cc=StoN(oper.top());
    ccc=StoN(c);
    //oper.pop;
    switch(Com[cc][ccc])
    {
     case 0:// <
      oper.push(c);
      c=s[++i];
      break;
     case 2:// =
      oper.pop();
      c=s[++i];
      break;
     case 1:// >
      theta=oper.top();
      oper.pop();
     
      bb=num.top();
      num.pop();
     
      aa=num.top();
      num.pop();
     
      num.push(Operate(aa,theta,bb));
      break;
    }
   }
}
return num.top();
}

int main()
{
int n,base;
char s[100];
while(1){
cout<<"输入表达式";
cin>>s;
cout<<"key="<<count(s)<<endl;
}


printf("\n");
system("pause");
}
//4+2*3-10/5 ac
//2+(3+4/2)*2 ac
//2*(3+4/2)*2 ac
//2*2+(3+4) ac
//1+(2+3) ac

ps:百度不支持tab,晕。。。