電卓のソースコードについて
Posted: 2020年11月22日(日) 22:59
#include<stdio.h>
char buf[10000];
int i;
char c;
int express();
int term();
int factor();
void next(){
while(buf[i]==' ')
i++;
c = buf[1++];
}
int express(){
int x = term();
while(c == '+' || c== '-'){
if(c == '+'){
next();
x = x + term();
} else if(c == '-'){
next();
x = x - term();
}
}
return x;
}
int term(){
int y = factor();
while(c== '*' || c== '/'){
if(c=='*'){
next();
y = y * factor();
}else if(c=='/'){
next();
y = y / factor();
}
}
return y;
}
int factor(){
int z = 0;
if(c == '('){
next();
z = express();
}else if(c >= '0' || c <= '9')
z = c - '0';
next();
return z;
}
int main(){
fgets(buf,127,stdin);
i = 0;
next();
printf("%d\n",express());
return 0;
}