求用C语言编写一个算术表达式的算法,如输入3*4+8-2键入Enter键输出18.

或者编写一个二叉树的遍历算法,最好把调试的截图一并发来。绝对给好评!!!

#include<iostream.h>
//#define MaxLen 100//存储空间
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;
}

void 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;
  }
  
 }

追问

在调试的过程中出现了这个错误,应该怎么解决啊?谢谢了!

追答

代码最后再加个大括号 }
这是结果:
./a.out
输入算术表达式:
3*4+8-2
转换成后缀表达式输出:
3#4#*8#+2#-
表达式求值:
18

追问

谢谢

温馨提示:答案为网友推荐,仅供参考
相似回答