表达式求值,一个字符串只由'+','-',和‘0’-‘9’组成,并且'+','-'只作为二元
运算符。
bool calculate(const char* exp, int &result);
bool calculate(const char* exp, int &result)
{
result = 0;
char str[50];
int i=0;
char op;
//get the first oprand
while (*exp && *exp != '+' && *exp != '-')
{
str[i++] = *exp++;
}
str[i] = 0;
i=0;
op = *exp;
exp++;
result = atoi(str);
while (*exp)
{
if (*exp == '+' || *exp == '-')
{
str[i] = 0;
switch (op)
{
case '+':
result += atoi(str); break;
case '-':
result -= atoi(str); break;
}
op = *exp;
i=0;
exp++;
}
str[i++]=*exp++;
}
switch (op)
{
case '+':
result += atoi(str); break;
case '-':
result -= atoi(str); break;
}
return true;
}
 
 
                    
                 

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号