⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 calculator.c

📁 unix环境下实现的cmm语言编译器
💻 C
字号:
/*calculator.c	Simple integer arithmetic calculator	according to the EBNF:		<exp> -> <term> { <addop> <term>}	<addop> -> + | -	<term> -> <pow> {<mulop> <pow>}	<mulop> -> * | / | %	<pow> -><factor> [<powop> <factor]	<powop> -> ^	<factor> ->[-]( ( <exp> ) | Number)		Inputs a line of text from stdin	Outputs "Eoor" or the result. *//*标准库函数声明*/int getchar(void);int printf(char *fmt, int);void exit(int);int puts(char *);int isdigit(char s);int sscanf(char *s, char *fmt, int *temp);char token; /* global token variable *//* function  prototypes for recursive calles */int expi(void);int	term(void);int factor(void);int powi(void);int pow(int, int);void error(void){	puts("Error\n");	exit(1);}void match(char expect){	if(token == expect)		token = getchar();	else		error();}int main(){	int result;	token = getchar();	/* load token with first 							character for lookahead */	result = expi();	if( token == '\n')	/*check for end of line */		printf("Result = %d\n", result);	else		error();	return 0;}int expi(void){	int temp = term();	while (token != '\n') {		if (token != '+')			if (token != '-')				break;		if (token == '+') {			match('+');			temp =  temp + term();			continue;		}		if (token == '-') {			match('-');			temp = temp - term();			continue;		}	}	return temp;}int term(void){	int temp = powi();	while (token != '\n') {		if (token != '*') if (token != '/') if (token != '%')			break;		if (token == '*') {			match('*');			temp = temp * powi();			continue;		}		if (token == '/') {			match('/');			temp = temp / powi();			continue;		}		if (token == '%') {			match('%');			temp = temp % powi();			continue;		}	}	return temp;}int powi(void){	int temp;	temp = factor();	if(token == '^') {		match('^');		temp = pow(temp, powi());	}	return temp;}int factor(void){	int temp;	char sig = 0;	if(token == '-') {		sig = '-';		match('-');			}	if(token == '(') {		match('(');		temp = expi();		match(')');	}	else if(isdigit(token)) {		char buf[25];		int i = 0;		while (i < sizeof buf){			buf[i] = token;			token = getchar();			i = i + 1;			if (!isdigit(token))				break;		}		buf[i] = 0;		sscanf(buf, "%d", &temp);	}		else		error();		if(sig == '-')		temp = -temp;	return  temp;}/*pow:计算x^n*/int pow(int x, int n){	int r = 1;	if (n == 0)		return 1;	while (n) {		r = r * x;		n = n - 1;	}	return r;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -