行云

行至水穷处,坐看云起时。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

表达式求值,一个字符串只由'+','-',和‘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;
}


 

posted on 2012-03-22 16:00  windflying  阅读(230)  评论(0)    收藏  举报