c语言括号匹配的检验问题,[讨论]括号匹配的检验

其实这个提 没有中括号大括号之分 就只有是() 就是先算内括号 在算外括号

你说的这个问题是非常麻烦的如果你能看懂下面的代码的话 你就可以明白了

如果你还是不明白,你就说一声 我会在给你解释的详细一些的

\*下面这个程序是我原来学数据结构的时候nuciewth斑竹给我的代码*/

#include

#define MAXSIZE 100

#include

int is_operation(char op)/*判断是否为运算符*/

{

switch(op)

{

case'+':

case'-':

case'*':

case'/':return(1);

default:return(0);

}

}

int priority(char op)/*判断进栈各运算符的优先级*/

{

switch(op)

{

case'#':return(-1);

case'(':return(0);

case'+':

case'-':return(1);

case'*':

case'/':return(2);

default:return(-1);

}

}

void postfix(char e[],char f[])/*中缀转换成后缀表达式*/

{

int i=0,j=0;

char opst[100];/*栈*/

int top,t;

top=0;/*当前顶指针*/

opst[top]='#';top++;/*将#放在栈底作为运算结束标志*/

while(e[i]!='#')/*核心语句段*/

{

if((e[i]>='0'&&e[i]<='9')||e[i]=='.')

{

f[j++]=e[i];/*遇到数字和小数点直接写入后缀表达式*/

}

else

if(e[i]=='(')/*遇到左括号直接写入操作符栈*/

{

opst[top]=e[i];

top++;

}

else

if(e[i]==')')/*遇到右括号和其对应的左括号后的操作符全部写入后缀表达式*/

{

t=top-1;

while(opst[t]!='(')

{

f[j++]=opst[--top];

t=top-1;

}

top--;/*出栈*/

}

else

if(is_operation(e[i]))

{

f[j++]=' ';

while(priority(opst[top-1])>=priority(e[i]))

{

f[j++]=opst[--top];

}

opst[top]=e[i];

top++;/*当前元素进栈*/

}

i++;/*处理下一个元素*/

}

while(top)

{

f[j++]=opst[--top];

}

f[j]='\0';

}

float readnumber(char f[],int *i)/*将字符转换为数值*/

{

float x=0.0;

int k=0;/*用K标记小数部分的位数*/

while(f[*i]>='0'&&f[*i]<='9')/*处理整数部分*/

{

x=x*10+(f[*i]-'0');

(*i)++;

}

if(f[*i]=='.')/*处理小数部分*/

{

(*i)++;

while(f[*i]>='0'&&f[*i]<='9')

{

x=x*10+(f[*i]-'0');

(*i)++;

k++;

}

}

while(k!=0)

{

x=x/10.0;

k=k-1;

}

/*printf("%f\n",x);*/

return(x);

}

double evalpost(char f[])

{

double x1,x2,obst[100];/*栈*/

int i=0,top=0;

while(f[i]!='#')/*还有元素要被处理*/

{

if(f[i]>='0'&&f[i]<='9')

{

obst[top]=readnumber(f,&i);

top++;/*将操作数进栈*/

}

else

if(f[i]==' ')/*用空格将两操作数隔开*/

{

i++;

}

else

if(f[i]=='+')/*做加法运算*/

{

x2=obst[--top];/*第一个操作数出栈*/

x1=obst[--top];/*第二个操作数出栈*/

obst[top]=x1+x2;/*两操作数进行运算,并将所得结果进栈*/

/*printf("%f",obst[top]); */

top++;

i++;

}

else

if(f[i]=='-')/*做减法运算*/

{

x2=obst[--top];

x1=obst[--top];

obst[top]=x1-x2;

top++;

i++;

}

else

if(f[i]=='*')/*做乘法运算*/

{

x2=obst[--top];

x1=obst[--top];

obst[top]=x1*x2;

top++;

i++;

}

else

if(f[i]=='/')/*做除法运算*/

{

x2=obst[--top];

x1=obst[--top];

obst[top]=x1/x2;

top++;

i++;

}

}

return(obst[0]);/*环回最终运算结果*/

}

int main()

{

char e[MAXSIZE],f[MAXSIZE];/*定义两个字符数组*/

double sum;/*结果*/

printf("please input the numbers,end by '#':");/*输入被操作的中缀表达式*/

scanf("%s",e);

postfix(e,f);/*将中缀表达式转换成后缀表达式*/

printf("the postfix sort:");

puts(f);

sum=evalpost(f);/*做运算*/

printf("Output the rezult:%f",sum);/*打印结果*/

return(0);

}

[此贴子已经被作者于2007-2-12 22:27:13编辑过]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值