HDU ACM 1237 简单计算器(栈)
http://acm.hdu.edu.cn/showproblem.php?pid=1237
题意:输入一个只有 +,-,*,/和数字的算式,输出计算结果,数字与符号之间以空格隔开.数据直到输入一行为0结束
输出为计算结果,结果保留小数点后两位.
一边输入,一边处理的方式.
用cin>>num输入第一个数后就开始处理
模拟中序表达式转换后续表达式
注: 有0+0的数据
View Code
1 #include <iostream> 2 #include <stack> 3 using namespace std; 4 5 struct FUN 6 { 7 char ch; 8 int lv; 9 }; 10 int main() 11 { 12 double num=0; 13 while(cin>>num) 14 { 15 char aa; 16 aa = getchar(); 17 if(num == 0 && aa == '\n') 18 { 19 break; 20 } 21 stack <FUN> ch; 22 stack <double> d; 23 24 d.push(num); 25 26 FUN c; 27 28 char a = 0; 29 while(1) 30 { 31 32 if(a == '\n') 33 { 34 while(!ch.empty()) 35 { 36 FUN mid = ch.top(); 37 ch.pop(); 38 double num1,num2,mid_num; 39 num2 = d.top(); 40 d.pop(); 41 num1 = d.top(); 42 d.pop(); 43 if(mid.ch == '+') 44 { 45 mid_num = num1 + num2; 46 } 47 if(mid.ch == '-') 48 { 49 mid_num = num1 - num2; 50 } 51 if(mid.ch == '*') 52 { 53 mid_num = num1 * num2; 54 } 55 if(mid.ch == '/') 56 { 57 mid_num = num1 / num2; 58 } 59 d.push(mid_num); 60 } 61 break; 62 } 63 cin>>c.ch; 64 getchar(); 65 if(c.ch == '-' ||c.ch == '+') 66 { 67 c.lv = 1; 68 } 69 else 70 { 71 c.lv = 2; 72 } 73 74 if(!ch.empty()) 75 { 76 FUN mid = ch.top(); 77 while(mid.lv >= c.lv) 78 { 79 ch.pop(); 80 double num1,num2,mid_num; 81 num2 = d.top(); 82 d.pop(); 83 num1 = d.top(); 84 d.pop(); 85 if(mid.ch == '+') 86 { 87 mid_num = num1 + num2; 88 } 89 if(mid.ch == '-') 90 { 91 mid_num = num1 - num2; 92 } 93 if(mid.ch == '*') 94 { 95 mid_num = num1 * num2; 96 } 97 if(mid.ch == '/') 98 { 99 mid_num = num1 / num2; 100 } 101 d.push(mid_num); 102 if(!ch.empty()) 103 { 104 mid = ch.top(); 105 } 106 else 107 { 108 break; 109 } 110 } 111 ch.push(c); 112 } 113 else 114 { 115 ch.push(c); 116 } 117 cin>>num; 118 d.push(num); 119 a = getchar(); 120 } 121 printf("%.2lf\n",d.top()); 122 } 123 return 0; 124 }