📄 calculator.cpp
字号:
/*
<exp>-><term>{<addop><term>}
<addop>->+|-
<term>-><factor>{<mulop><factor>}
<mulop>->*
<factor>->(<exp>)|Number
从stdin输入一文本行;
输出"Error"或计算结果。
*/
//#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char token;
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(/*int argc, _TCHAR* argv[]*/)
{ int result;
token=getchar();
result=exp();
if(token=='\n'){
printf("Result = %d\n",result);
}
else error();
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;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -