求大神!!表达式顺序求值
表达式求值(Expression Evaluation) 编写程序对表达式求值。Enter an expression: 1+2.53
Value of expression: 10.5
表达式中的操作数是浮点数,运算符是+、-、和/。表达式从左向右求值(所有运算符的优先级都⼀样)。
输出范例:
Enter an expression: 2+3*4-5/2
Value of expression: 7.5
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> struct type { float num1; float num2; int sign; }; int main() { char str[60],tmp; struct type sub={0}; int i=0,flag=0,flag_dot=0; printf("请输入表达式:"); gets(str); while(1) { strncpy(&tmp,str+i,1); if(tmp=='\0')break; i++; switch(tmp) { case '+': { if(flag==1) { switch(sub.sign) { case 1:{sub.num2=sub.num2+sub.num1;break;} case 2:{sub.num2=sub.num2-sub.num1; break;} case 3:{sub.num2=sub.num2*sub.num1;break;} case 4:{sub.num2=sub.num2/sub.num1;break;} default:{printf("输入错误!\n");exit(1);} } } else { flag=1; sub.num2=sub.num1; } sub.num1=0; sub.sign=1; flag_dot=0; break; } case '-': { if(flag==1) { switch(sub.sign) { case 1:{sub.num2=sub.num2+sub.num1;break;} case 2:{sub.num2=sub.num2-sub.num1; break;} case 3:{sub.num2=sub.num2*sub.num1;break;} case 4:{sub.num2=sub.num2/sub.num1;break;} default:{printf("输入错误!\n");exit(1);} } } else { flag=1; sub.num2=sub.num1; } sub.num1=0; sub.sign=2; flag_dot=0; break; } case '*': { if(flag==1) { switch(sub.sign) { case 1:{sub.num2=sub.num2+sub.num1;break;} case 2:{sub.num2=sub.num2-sub.num1; break;} case 3:{sub.num2=sub.num2*sub.num1;break;} case 4:{sub.num2=sub.num2/sub.num1;break;} default:{printf("输入错误!\n");exit(1);} } } else { flag=1; sub.num2=sub.num1; } sub.num1=0; sub.sign=3; flag_dot=0; break; } case '/': { if(flag==1) { switch(sub.sign) { case 1:{sub.num2=sub.num2+sub.num1;break;} case 2:{sub.num2=sub.num2-sub.num1; break;} case 3:{sub.num2=sub.num2*sub.num1;break;} case 4:{sub.num2=sub.num2/sub.num1;break;} default:{printf("输入错误!\n");exit(1);} } } else { flag=1; sub.num2=sub.num1; } sub.num1=0; sub.sign=4; flag_dot=0; break; } case '.':{flag_dot=1;break;} default: { if(tmp>=48&&tmp<=57) { if(flag_dot>0) { sub.num1=sub.num1+(float)(tmp-48)/pow(10,flag_dot); //printf("num1=%.2f,tmp=%d,flag_dot=%d\n",sub.num1,tmp,flag_dot); flag_dot++; } else sub.num1=sub.num1*10+tmp-48; break; } else { printf("输入错误!\n"); exit(1); } } } //printf("num1=%.2f,num2=%.2f,sign=%d\n",sub.num1,sub.num2,sub.sign); }; switch(sub.sign) { case 1:{sub.num2=sub.num2+sub.num1;break;} case 2:{sub.num2=sub.num2-sub.num1;break;} case 3:{sub.num2=sub.num2*sub.num1;break;} case 4:{sub.num2=sub.num2/sub.num1;break;} default:{printf("输入错误!\n");exit(1);} } printf("表达式的值为%.4f",sub.num2); return 0; }