注册 登录
编程论坛 C++教室

表达式求值,各位帮帮忙。。

小茫 发布于 2010-10-24 20:26, 530 次点击
程序代码:
#include<stdio.h>
#include<string.h>

int rank(char c1,char c2)          //判断符号的优先级
{
    if(c1=='(')return -1;
    if(c1==')')return 1;
    if(c2=='(')return -1;
    if(c2==')')return 1;
    if(c1=='(' && c2==')')return 0;
    if(c1=='#' && c2=='#')return 0;
    if(c1=='#')return -1;
    if(c2=='#')return 1;
    if(c2=='/' && c1=='+' )return -1;
    if(c2=='/' && c1=='-' )return -1;
    if(c2=='*' && c1=='+' )return -1;
    if(c2=='*' && c1=='-' )return -1;

    return 1;
}

void change(char sin[],char sout[])       //将中缀表达式转换成后缀表达式
{
    char  op[99];
    int len,i,psout=0,pop=1,j=0;

    len=strlen(sin);
    op[0]='#';
    sin[len++]='#';
    for(i=0;i<len;i++)
    {
        scanf("%s",&sin[i]);
        if(sin[i]>='0' && sin[i]<='9')
            sout[psout++]=sin[i];
        else
        {
            while(rank(op[pop],sin[i])>0)
            {
                sout[psout++]=op[pop-1];
                pop--;
            }
            if(rank(op[pop],sin[i])==0)
                pop--;
            if(rank(op[pop],sin[i])<0)
                op[pop++]=sin[i];
        }
    }
    sout[psout]=0;
    while(sout[j])
    {
        j++;
        printf("后缀表达式为:%s",sout[j]);
    }
    return;
}

double sincal(double a,double b,char c)     //将运算符和操作数的运行结果返回
{
    if(c=='+')return(a+b);
    if(c=='-')return(a-b);
    if(c=='*')return(a*b);
    return(a/b);
}

double calculate(char cal[])        //计算后缀表达式
{
    int i=0,len,top=0;
    double inter[99],a,b;

    len=strlen(cal);
    for(i=0;i<len;i++)
    {
        if(cal[i]>'0' && cal[i]<'9')
            inter[++top]=cal[i]-'0';
        else
        {
            a=inter[top-2];
            b=inter[top-1];
            inter[top-2]=sincal(a,b,cal[i]);
            top--;
        }
    }
     return inter[0];
}

void main()
{
    printf("输入一个表达式:");

    double  final;
    char  sin[99],sout[99];
    scanf("%s",sin);
    change(sin,sout);
    final=calculate(sout);

    printf("%f\n",final);
}
看了好久,脑袋都要坏掉了
3 回复
#2
lyj2010lyj2010-10-24 20:59
printf("%f\n",final);
改了:printf("%f"\n,final)
#3
sunmingchun2010-10-24 21:14
错误改了出来了,可是没结果,有时间好好看看。
#4
小茫2010-10-24 21:28
抱歉没说清楚,这个程序的意思是让用户输入一个中缀表达式,然后通过栈将它转为后缀表达式之后,再输出这个表达式的结果。
楼上的说错误改出来了,但是没结果是什么意思?
二楼说的那个算是错误码?/n不是本来就要在双引号里面的吗?
1