登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

秒大刀 博客

好好学习 天天向上

 
 
 

日志

 
 
 
 

Recursive Descent Calulator [C]  

2006-02-25 22:30:35|  分类: 技术积累 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

//Simple intger arithmetic calculator according to the EBNF:

//  <exp> -> <term>{<addop><term>}

//  <addop> -> +|-

//  <term> -> <factor>{<mulop><factor>}

//  <mulop> -> *

//  <factor> -> (<exp>)|Number

//

//  Inputs a line of text from stdin

//  Outputs "ERROR" or the result.

 

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

 

char token; //global token variable

//function prototypes for recursive call;

int exp(void);

int term(void);

int factor(void);

 

void error(void)

{

    fprintf(stderr, "Error\n");

    exit(1);

}

 

void match(char expectedToken)

{

    if(token == expectedToken)

        token = getchar();

    else

        error();

}

 

int main()

{

    while(1)

    {

        int result;

        printf("请输入算式(可以包含整数的 \'+\' \'-\' \'*\' \')\' \'(\')运算:\n");

        token = getchar();//load token with first character for lookahead

        result = exp();

        if(token == '\n')//check for end of line

            printf("Result = %d\n", result);

        else

            error();//extraneous chars on line

    }

    return 0;

}

 

int exp(void)

{

    int temp = term();

    while((token == '+')||(token == '-'))

    {

        switch(token)

        {

        case '+':

            match('+');

            temp += term();

            break;

        case '-':

            match('-');

            temp -= term();

            break;

        }

    }

    return temp;

}

 

int term(void)

{

    int temp = factor();

    while(token == '*')

    {

        match('*');

        temp *= factor();

    }

    return temp;

}

 

int factor(void)

{

    int temp;

    if(token == '(')

    {

        match('(');

        temp = exp();

        match(')');

    }

    else if(isdigit(token))

    {

        ungetc(token, stdin);

        scanf("%d", &temp);

        token = getchar();

    }

    else

        error();

    return temp;

}

  评论这张
 
阅读(885)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018