标题:堆栈解决表达式求值代码,问题在?
只看楼主
zzxwill
Rank: 1
等 级:新手上路
帖 子:398
专家分:0
注 册:2007-8-15
 问题点数:0 回复次数:0 
堆栈解决表达式求值代码,问题在?
#include <stdio.h>
//算法2.11
//使用堆栈的顺序存储结构
char Precede(char ch1,char ch2);
int Operate(int m,char ch,int n);
main()
{
    char OPTR[100];
    char OPND[100];
    char c,cpri;
    int i,j;
    i=j=0;
    OPTR[0]='#';
    c=getchar();
    while(c!='#'||OPTR[i]!='#'){
        cpri=c;
        c=getchar();
        if(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c=='#'||c==')'){
            switch(Precede(c,cpri)){
                case '<':
                    OPTR[++i]=c;
                case '=':
                    OPTR[i]='\0';
                    cpri=OPTR[i--];
//                    c=getchar();
//                    OPTR[++i]=c;
                    break;

                case '>':
                    OPND[j]=Operate(OPND[j-1],c,OPND[j]);
                    break;


            }
        }
        else
            OPND[j++]=c-'0';
    }
    printf("%d",OPND[0]);



}


//下面这个函数判断两个算符的优先级
char Precede(char ch1,char ch2){
    if( (ch1=='+'||ch1=='-'||ch1=='*'||ch1=='/'||ch1=='('||ch1=='#')&&ch2=='('
        ||(ch1=='+'||ch1=='-'||ch1=='('||ch1=='#')&&(ch2=='/'||ch2=='*')
        ||(ch1=='('||ch1=='#')&&(ch2=='+'||ch2=='*') ){
        return '<';
    }
    else if(ch1=='('&&ch2==')'||ch1=='#'&&ch2=='#'){
        return '=';
    }
    else
        return '>';
}

//下面这个函数为进行二元运算m OP n
int Operate(int m,char ch,int n){
    switch(ch){
    case '+':
        return m+n;
        break;
    case '-':
        return m-n;
        break;
    case '*':
        return m*n;
        break;
    case '/':
        return m/n;
        break;
    }
}
搜索更多相关主题的帖子: 堆栈 求值 char OPTR int 
2007-12-04 21:06



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-190412-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.153022 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved