表达式求值

来源:互联网 发布:linux命令cp 编辑:程序博客网 时间:2024/06/15 05:55
#include<iostream>
//#define MaxLen 100//存储空间
using namespace std;
int tran(char str[], char expr[])   //将中缀表达式转换成后缀表达式   if(tran(str,expr)==0)//原来表达式,后缀表达式
{
 int st[100];   //转化过程使用的过渡栈
 char ch;
 int i=0,exindex=0,stindex=-1;  //i是str下标,exindex是expr下标,stindex是st下标
 while((ch=str[i++])!='\0')
 {
  if(ch>='0' && ch<='9')   //判断是数字
  {
   expr[exindex]=ch;   //压栈
   exindex++;   //栈顶指针上移
   while((ch=str[i++])!='\0' && ch>='0' && ch<='9')   //其它位依次入栈
   {
    expr[exindex]=ch;
    exindex++;
   }
   i--;   //str原算术表达式栈向下遍历
   expr[exindex]='#';   //以特殊字符“#”表示结束
   exindex++;
  }
     else if(ch=='(')   //判断为左括号
  {
   stindex++;
   st[stindex]=ch;
  }
     else if(ch==')')    //判断为右括号
  {
   while (st[stindex]!='(')
   {
    expr[exindex]=st[stindex];
    stindex--;   //依次弹出
    exindex++;
   }
   stindex--;//'('出栈
  }
     else if(ch=='+' || ch=='-')//判断为加减号
  {
   while(stindex>=0 && st[stindex]!='(')
   {
    expr[exindex]=st[stindex];
    stindex--;
    exindex++;
   }
   stindex++;
   st[stindex]=ch;
  }
     else if (ch=='*' || ch=='/')//判断为乘除号
  {
   while(st[stindex]=='*' || st[stindex]=='/')
   {
    expr[exindex]=st[stindex];
    stindex--;
    exindex++;
   }
   stindex++;
   st[stindex]=ch;
  }
 }
 while (stindex>=0)//将栈中所有运算符依次弹出存入expr栈中
 {
  expr[exindex]=st[stindex];
  exindex++;
  stindex--;
 }
 expr[exindex]='\0';
 return 1;
}
int compvalue(char expr[],int *n)
{
 int st[100],d;   //st为数栈
 char ch;
 int exindex=0,stindex=-1;  //exindex是expr下标,stindex是st的下标
 while((ch=expr[exindex++])!='\0')
 {
  if(ch>='0'&&ch<='9')//将数字字符转换成数字
  {
   d=0;
   do
   {
    d=10*d+ch-'0';
   }
   while((ch=expr[exindex++])!='#');
   stindex++;
   st[stindex]=d;//数字进栈
  }
  else//运算符操作
  {
   switch(ch)
   {
   case'+':st[stindex-1]=st[stindex-1]+st[stindex];
    break;
   case'-':st[stindex-1]=st[stindex-1]-st[stindex];
    break;
   case'*':st[stindex-1]=st[stindex-1]*st[stindex];
    break;
   case'/':
    if(st[stindex]!=0)
    { st[stindex-1]=st[stindex-1]/st[stindex]; }
    else return 0;  //除0错误!
    break;
   }
   stindex--;
  }
 }
 (*n)=st[stindex];
 return 1;
}

int main()
{
 char str[100];   //存储原来算术表达式
 char expr[100];   //存储转换成的后缀表达式
 int n;
 cout<<"输入算术表达式:"<<endl;
 cin>>str;
 if(tran(str,expr)==0)
 {
  cout<<"原算术表达式不正确!"<<endl;
 }
 else
 {
  cout<<"转换成后缀表达式输出:"<<endl<<expr<<endl;
  if(compvalue(expr,&n)==1)
  {
   cout<<"表达式求值:"<<endl<<n<<endl;
  }
  else
  {
   cout<<"计算错误!"<<endl;
  }

 }
 return 0; }
0 0
原创粉丝点击