用一个pre储存之前运算过的数,用prec处理temp之前的符号,用temp存储现在正在运算的数,注意一下细节就好。
http://acm.hdu.edu.cn/showproblem.php?pid=1237
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int a[205];
char b[205];
int main(void){
//freopen("a.in","r",stdin);
int i,lena;
char tempc,prec;
double pre,temp;
while(~scanf("%d",a)){
tempc = getchar();
if(tempc == '\n'&&a[0]==0)break;
for(i=1;tempc!='\n';i++){
scanf("%c %d",b+i,a+i);
tempc = getchar();
}
lena = i;
pre = 0;
prec = '+';
temp = a[0];
for(i=1;i<lena;i++){
if(b[i]=='-'){
if(prec == '+') pre = pre + temp;
else pre = pre - temp;
prec = '-'; temp = a[i];
}
else if(b[i]=='+'){
if(prec == '+') pre = pre + temp;
else pre = pre - temp;
prec = '+'; temp = a[i];
}
else if(b[i]=='*'){
temp = temp * a[i];
}
else {
temp = temp / a[i];
}
}
if(prec == '+')pre = pre + temp;
else pre = pre - temp;
printf("%.2lf\n",pre);
}
return 0;
}