zoukankan      html  css  js  c++  java
  • 一个计算器的C语言实现

    今天在读《编译原理及实践》时。看到了一个简单的整数计算器的实现。

    依照书上的思路,我略微进行了扩展:

    1、从整数计算器扩展到小数计算器。

    2、支持除法

    3、支持空字符。

    执行效果例如以下:


    代码非常easy,例如以下:

    cal.c:

    #include <stdio.h>
    #include <stdlib.h>
    
    char token;
    
    double exp(void);
    double term(void);
    double factor(void);
    char getPrintableChar(void);
    
    void match(char expectedToken);
    void error(void);
    
    
    int main(void)
    {
    	double result;
    
    	for (;;)
    	{
    		token = getPrintableChar();
    		if (token == 'q')
    			break;
    
    		result = exp();
    		if (token == '
    ')
    			printf("Result is: %g
    ", result);
    		else
    			error();
    	}
    
    	return 0;
    }
    
    double exp(void)
    {
    	double temp = term();
    	while (token == '+' || token == '-')
    		switch(token)
    		{
    			case '+': match('+');
    					  temp += term();
    					  break;
    			case '-': match('-');
    					  temp -= term();
    					  break;
    		}
    	return temp;
    }
    
    double term(void)
    {
    	double temp = factor();
    	while (token == '*' || token == '/')
    		switch(token)
    		{
    			case '*': match('*');
    					  temp *= factor();
    					  break;
    			case '/': match('/');
    					  temp /= factor();
    					  break;
    		}
    	return temp;
    }
    
    double factor(void)
    {
    	double temp;
    	if (token == '(')
    	{
    		match('(');
    		temp = exp();
    		match(')');
    	} else if (isdigit(token))
    	{
    		ungetc(token, stdin);
    		scanf("%lf", &temp);
    		token = getPrintableChar();
    	} else
    		error();
    
    	return temp;
    }
    
    void error(void)
    {
    	fprintf(stderr, "Error!
    ");
    	exit(EXIT_FAILURE);
    }
    
    void match(char expectedToken)
    {
    	if (expectedToken == token)
    		token = getPrintableChar();
    	else
    		error();
    }
    
    char getPrintableChar(void)
    {
    	char temp;
    	do
    		temp = getchar();
    	while (isblank(temp));
    
    	return temp;
    }
    

    程序实现的思路是依照EBNF规则实现,即:

    <exp> -> <term> { <addop> <term> }
    <addop> -> + | -
    <term> -> <factor> { <mulop> <factor> }
    <mulop> -> * | /
    <factor> -> ( <exp> ) | Number

    关于EBNF, 能够參考书上的内容。在这里就不赘述了。

  • 相关阅读:
    【线段树 树链剖分 差分 经典技巧】loj#3046. 「ZJOI2019」语言【未完】
    【图论 思维】cf715B. Complete The Graph加强
    【A* 网络流】codechef Chef and Cut
    【主席树上二分】bzoj5361: [Lydsy1805月赛]对称数
    蓝书例题之UVa 10253 Series-Parallel Networks
    HAOI2019+十二省联考 游记
    Beyas定理
    CF739E Gosha is hunting DP+wqs二分
    wqs二分
    线性规划之单纯形算法
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5134565.html
Copyright © 2011-2022 走看看