C语言实现计算器(基于EBNF表达式和递归下降思想)

 之前笔者大一寒假闲来无事基于波兰表达式和平衡符号做了一个功能强大的计算器

上一篇文章点这里--“C++实现计算器”

最近编译原理的老师要求用递归下降的思想对表达式进行语法分析,笔者顺带完善了一点点计算的小功能---在这里笔者非常感谢 编译原理及实践 这本书

代码注释清晰,加之递归下降的思路也不难,笔者就去睡觉啦~ 

#define _CRT_SECURE_NO_WARNINGS
/*Simple integer/float arithmetic calculator
  according to the EBNF:

  <exp> -> <modexp> { <addop> <modexp> }
  <addop> -> + | -
  <modexp> -> <mulexp> { <modop> <mulexp> }
  <modop> -> %
  <mulexp> -> <brkexp> { <mulop> <brkexp> }
  <mulop> -> * | /
  <brkexp> -> ( <exp> ) | Number

  Inputs a line of text from stdin
  Outputs "Error" or the result.
 */


#include <stdlib.h> 
#include <stdio.h>

FILE* in;
char token; /* global token variable */
int right = 1; /* 0 for false, 1 for right */

/* function prototypes for recursive calls */
float exp(void);
float modexp(void);
float mulexp(void);
float brkexp(void);

void error(void) {
	fprintf(stderr, "Error\n");
}

void match(char expectedToken) {
	if (token == expectedToken)
		while ((token = getc(in)) == ' ') {}
	else {
		right = 0;
	}
}

main()
{
	in = fopen("test.txt", "r");
	float result;
	while ((token = getc(in)) != EOF) { /* end with '#' */
		result = exp();
		if (token == '\n' && right) /* right is to prevent errors in the middle */
			printf("Result = %f\n", result);
		else {
			error();
			right = 1;
			if (token == '\n')
				continue;
			else {
				while ((token = getc(in)) != '\n') {} /* traverse to the end */
			}
		}
	}
	return 0;
}

float exp(void) {
	float tmp = modexp();
	while (token == '+' || token == '-') {
		switch (token) {
		case '+':
			match('+');
			tmp += modexp();
			break;
		case '-':
			match('-');
			tmp -= modexp();
			break;
		}
	}
	return tmp;
}

float modexp(void) {
	float tmp = mulexp();
	while (token == '%') {
		match('%');
		float TMP = mulexp();
		tmp = tmp - (int)(tmp / TMP) * TMP;
	}
	return tmp;
}

float mulexp(void) {
	float tmp = brkexp();
	while (token == '*' || token == '/') {
		switch (token) {
		case '*':
			match('*');
			tmp *= brkexp();
			break;
		case '/':
			match('/');
			tmp /= brkexp();
			break;
		}
	}
	return tmp;
}

float brkexp(void) {
	float tmp = 0;
	if (token == '(') {
		match('(');
		tmp = exp();
		match(')');
	}
	else if (isdigit(token)) {
		ungetc(token, in);
		fscanf(in, "%f", &tmp);
		while ((token = getc(in)) == ' ') {}
	}
	else {
		right = 0;
	}
	return tmp;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值