#include <stdio.h> #include <string.h> #include <stdlib.h> #define maxn 1000 char buf[maxn], str[maxn], signStack[maxn], ch[2]; int len, id, idSign, idAns, i, n; double ans[maxn]; void checkSign(char sign){ if(sign == '(') signStack[idSign++] =
时间: 2024-01-28 11:04:44 浏览: 63
#include <stdio.h>
sign;
else if(sign == ')'){
while(signStack[idSign-1] != '('){
char op = signStack[--idSign];
double b = ans[--idAns], a = ans[--idAns];
if(op == '+') ans[idAns++] = a + b;
else if(op == '-') ans[idAns++] = a - b;
else if(op == '*') ans[idAns++] = a * b;
else if(op == '/') ans[idAns++] = a / b;
}
idSign--;
}
else if(sign == '+' || sign == '-'){
while(idSign > 0 && signStack[idSign-1] != '('){
char op = signStack[--idSign];
double b = ans[--idAns], a = ans[--idAns];
if(op == '+') ans[idAns++] = a + b;
else if(op == '-') ans[idAns++] = a - b;
else if(op == '*') ans[idAns++] = a * b;
else if(op == '/') ans[idAns++] = a / b;
}
signStack[idSign++] = sign;
}
else if(sign == '*' || sign == '/'){
while(idSign > 0 && (signStack[idSign-1] == '*' || signStack[idSign-1] == '/')){
char op = signStack[--idSign];
double b = ans[--idAns], a = ans[--idAns];
if(op == '*') ans[idAns++] = a * b;
else if(op == '/') ans[idAns++] = a / b;
}
signStack[idSign++] = sign;
}
}
int main(){
while(fgets(buf, maxn, stdin) != NULL){
len = strlen(buf);
id = idSign = idAns = 0;
memset(ans, 0, sizeof(ans));
memset(signStack, 0, sizeof(signStack));
for(i = 0; i < len; i++){
if(buf[i] == ' ' || buf[i] == '\n') continue;
if(buf[i] >= '0' && buf[i] <= '9'){
n = 0;
while(buf[i] >= '0' && buf[i] <= '9'){
n = n * 10 + buf[i] - '0';
i++;
}
ans[idAns++] = (double)n;
i--;
}
else{
checkSign(buf[i]);
}
}
while(idSign > 0){
char op = signStack[--idSign];
double b = ans[--idAns], a = ans[--idAns];
if(op == '+') ans[idAns++] = a + b;
else if(op == '-') ans[idAns++] = a - b;
else if(op == '*') ans[idAns++] = a * b;
else if(op == '/') ans[idAns++] = a / b;
}
printf("%.2f\n", ans[0]);
}
return 0;
}
请问这段代码实现了什么功能?
阅读全文