求c语言编写四则运算程序

2024-11-16 06:58:40
推荐回答(2个)
回答1:

#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;
}

回答2:

分少