C程序检查表达式的有效性

时间:2014-09-25 23:27:16

标签: c

plz帮我找到这个程序中的错误.... 这是错误的...... 如果表达式有效,则返回1,否则为0 .... 然后...

/* Check for balanced parentheses in an expression */
int chkexp(char exp[], int N)
{
  char arr[N];
  int top = 0, rslt, i;
  for (i = 0; i < N; i++)
    { 
      if ((exp[i] == '(') || (exp[i]=='{') || (exp[i]=='['))
        {
          arr[top] = exp[i];
          top = top + 1;
        }
      else if ((exp[i] == ')') || (exp[i] == '}') || (exp[i] == ']'))
        { 
          if (arr[top] == exp[i])
            {
              --top;
              rslt = 1;
            }
          else
            {
              rslt = 0;
              break;
            } 
        }
    }
  if (top > 0)
    rslt = 0;
  return rslt;
}

2 个答案:

答案 0 :(得分:3)

if(arr[top]==exp[i]) - 好吧,那不行,是吗?例如。 '('不等于')'。

答案 1 :(得分:0)

您失败的主要原因当然是复制arr[top]中的值然后再增加top,然后下次尝试与'arr [top]&#39;进行比较时哪个没有初始化!!

无论如何,即使你解决了这个问题,你也会因为500 -Internal Server Erro所说的而崩溃!我建议你比较(ASCII)值,看看我注意到的ASCII table

  • '(' = 40')' = 41
  • '[' = 91']' = 93
  • '{' = 123'}' = 125

因此像if ( close - open >= 0 && close - open <= 2)这样的条件会满足。

我在您的代码中所做的细微更改是:

  • rslt初始化为0并仅在成功的情况下进行更改。
  • 请勿使用整个数组来存储一个char并与之进行比较。
int
chkexp(const char *const exp, const int N)
{
  /* char arr[N];  no need */
  char type;  /* to check type of expression () [] {} */
  int rslt = 0;  /* initialize result to false */
  int i;  /* loop index */
  for (i = 0; i < N; i++)
    {
      if((exp[i] == '(') || (exp[i] == '{') || (exp[i] == '['))  /* when find opening */
        {
          type = exp[i];  /* type contains either '(' or '[' or '{' */
        }
      else if ((exp[i] == ')') || (exp[i] == '}') || (exp[i] == ']'))  /* when find closing */
        {
          if(exp[i] - type <= 2 && exp[i] - type >= 0)
            {
              rslt = 1;  /* the only case rslt flips to 1 */
            }
          break;
        }
    }

  return rslt;
}