读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
Sample Output
3.00 13.36
1 #include<iostream> 2 #include<stack> 3 #include<cstring> 4 #include<stdlib.h> 5 using namespace std; 6 7 int judge(char c) 8 { 9 if(c==‘+‘||c==‘-‘||c==‘*‘||c==‘/‘||c==‘=‘) 10 return 1; 11 12 return 0; 13 } 14 char Precede(char a,char b) 15 { 16 if(a==‘*‘||a==‘/‘)a=‘*‘; 17 if(b==‘*‘||b==‘/‘)b=‘*‘; 18 if(a==‘+‘||a==‘-‘)a=‘+‘; 19 if(b==‘+‘||b==‘-‘)b=‘+‘; 20 if(a==‘#‘)return ‘<‘; 21 if(b==‘=‘)return ‘>‘; 22 if(a==‘+‘&&b==‘+‘){return ‘>‘;} 23 else if(a==‘+‘&&b==‘*‘)return ‘<‘; 24 else if(a==‘*‘&&b==‘*‘)return ‘>‘; 25 else if(a==‘*‘&&b==‘+‘)return ‘>‘; 26 } 27 28 double operat(double n1,double n2,char e) 29 { 30 switch(e) 31 { 32 case ‘+‘:return (n1+n2); 33 case ‘-‘:return (n1-n2); 34 case ‘*‘:return (n1*n2); 35 case ‘/‘:return (n1/n2); 36 } 37 } 38 int main() 39 { 40 char a[205]; 41 int j; 42 while(1) 43 { 44 gets(a); 45 if(strcmp(a,"0")==0)break; 46 stack<double>num; 47 stack<char>ch; 48 j=0; 49 char b[205]; 50 ch.push(‘#‘); 51 int i=0; 52 for(i=0;a[i]!=‘\0‘;i++); 53 a[i]=‘=‘; 54 i=0; 55 while(a[i]!=‘=‘||ch.top()!=‘#‘) 56 { 57 if(a[i]==‘ ‘) 58 {i++;} 59 else if(judge(a[i])==1) 60 { 61 switch(Precede(ch.top(),a[i])) 62 { 63 case ‘<‘:ch.push(a[i]);i++;break; 64 case ‘>‘: 65 char e=ch.top(); 66 ch.pop(); 67 double n2=num.top(); 68 num.pop(); 69 double n1=num.top(); 70 num.pop(); 71 num.push(operat(n1,n2,e)); 72 } 73 //ch.push(a[i]); 74 } 75 else if(a[i]>=‘0‘&&a[i]<=‘9‘) 76 { 77 double s=0; 78 while(a[i]>=‘0‘&&a[i]<=‘9‘) 79 { 80 s=s*10+a[i]-‘0‘; 81 i++; 82 } 83 num.push(s); 84 } 85 } 86 printf("%.2lf\n",num.top()); 87 while(!num.empty()) 88 { 89 num.pop(); 90 } 91 while(!ch.empty()) 92 { 93 ch.pop(); 94 } 95 } 96 return 0; 97 }
原文:https://www.cnblogs.com/qq-1423406156/p/11939605.html