#include"stdafx.h"
#include
#include
#include
char token;/*global token variable*/
/*function prototypes for recursive calls*/
float exp(void);
float term(void);
float factor(void);
void error(void)
{
fprintf(stderr,"Error\n");
exit(1);
}
void match(char expectedToken)
{
if(token==expectedToken)token=getchar();
else error();
}
calculate()
{
float result;
token = getchar();/*load token with first character for lookahead*/
result = exp();
if(token=='\n')/*check for end of line */
printf("Result = %.2f\n",result);
else error();/*extraneous cahrs on line*/
}
main()
{
do
{
calculate();
}while(1);
}
float exp(void)
{
float temp = term();
while((token=='+')||(token=='-'))
switch(token)
{
case '+':
match('+');
temp+=term();
break;
case '-':
match('-');
temp-=term();
break;
}
return temp;
}
float term(void)
{
float temp = factor();
while ((token=='*')||(token=='/'))
switch(token)
{
case '*':
match('*');
temp*=factor();
break;
case '/':
match('/');
temp/=factor();
break;
}
return temp;
}
float factor(void)
{
float temp;
if(token=='('){
match('(');
temp = exp();
match(')');
}
else if(isdigit(token)){
ungetc(token,stdin);
scanf("%f",&temp);
token = getchar();
}
else error();
return temp;
}
分少