使用递归方法设计的表达式计算器程序

#include<stdio.h>
char token; /*全局变量*/
int main()
{
  int low();
  int result;
  printf("*******************************************/n");
  printf("** Welcome to use this simple calculator **/n");
  printf("** Please input a multinomial like       **/n");
  printf("**        16-{2*[3*(5-1)/2+14]+9}/7       **/n");
  printf("*******************************************/n");
  token=getchar(); /*载入第一个符号*/
  result=low(); /*进行计算*/
  if(token=='/n')printf("The answer is:%d/n",result);
  else
  {
    printf("Unexpected char!");
    exit(1);
  }
  scanf("%d",result);
  return 0;
}
/*对当前的标志进行匹配*/
void match(char expectedToken)
{
  if(token==expectedToken)token=getchar();/*匹配成功,获取下一个标志*/
  else
  {
    printf("cannot match/n");
    exit(1);/*匹配不成功,退出程序*/
  }
}
/*用于计算表达式中的+、-运算*/
int low()
{
  int result=mid();
  while(token=='+'||token=='-')
       if(token=='+')
       {
         match('+');
         result+=mid();
       }
       else if(token=='-')
       {
         match('-');
         result-=mid();
       }
  return result;
}
/*用于计算表达式中的*、/运算*/
int mid()
{
  int div;
  int result=high();
  while(token=='*'||token=='/')
  if(token=='*')
  {
    match('*');
    result*=high();
  }
  else if(token=='/')
  {
    match('/');
    div=high();
    if(div==0)  /*需要判断除数是否为0*/
    {
      printf("cannot is 0");
      exit(1);
    }
    result/=div;
  }
  return result;
}
/*用于计算表达式中带{}的运算*/
int high()
{
  int result=high2();
  if(token=='{')
  {
    match('{');
    result=low(); /*递归计算表达式*/
    match('}');
  }
  return result;
}
/*用于计算表达式中带[]的运算*/
int high2()
{
  int result=high3();
  if(token=='[')
  {
    match('[');
    result=low(); /*递归计算表达式*/
    match(']');
  }
  return result;
}
/*用于计算表达式中带()的运算*/
int high3()
{
  int result=mathinput();
  if(token=='(')
  {
    match('(');
    result=low(); /*递归计算表达式*/
    match(')');
  }
  return result;
}
/*获取计算数值*/
int mathinput()
{
  int result=0;
   if(token>='0'&&token<='9')
   {
    ungetc(token,stdin); /*将读入的字符退还给输入流,为读取整个数*/
    scanf("%d",&result); /*读出数字*/
    token=getchar(); /*读出当前的计算标志*/
    }
  return result;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值