/*
* 《算法笔记》p245 第七章 提高篇(1)————数据结构专题(1)
* 7.1 栈的应用:【Codeup 1918】简单计算器
* http://codeup.cn/problem.php?cid=100000605&pid=0
* 题目描述:读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
*
* 思路(王道):
* (1)两个栈,符号栈和数字栈。两个哨兵'#'和'¥','#'压入栈底,'¥'接在串后,优先级'¥'>'#'。
* (2)优先级获得函数:'#'=0,'¥'=1,'+''-'=2,'*''/'=3。
* (3)获取数字函数
* (4)加减乘除计算函数
* (5)遍历字符串,遇到空格则跳过;遇到数字则压入数字栈;
* 如果遇到的是符号,则比较当前op与操作符栈顶opTop的优先级
* 1)若果op>opTop,则将op入栈
* 2)如果op<=opTop,则弹出opTop,并弹出数字stack的栈顶和次栈顶,次栈顶为参与运算的在前数字,栈顶数字在后。
* 计算结果存入数字stack。
* (6)直到遍历结束,此时操作符stack中只剩'¥''#',且此时数字stack中只剩一个元素,即为结果。
*/
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
int Priority(char c){
if (c == '#'){
return 0;
}else if (c == '$'){
return 1;
}else if (c == '+'|| c == '-'){
return 2;
}else{
return 3;
}
}
double GetNumber(string str,int& index){//int& 为引用型,可以改变传递过来的参数本身的值,它们指向同一地址
double number = 0;
while(isdigit(str[index])){
number = number*10 + str[index]-'0';//注意char转为int
index++;
}
return number;
}
double Calculate(double x,double y,char op){
double result = 0;
if(op=='+'){
result= x+y;
}else if(op=='-'){
result= x-y;
}else if(op=='*'){
result= x*y;
}else if(op=='/'){
result= x/y;
}
return result;
}
int main(){
string str;
while(getline(cin,str)){
if(str == "0"){
break;
}
int index = 0;
stack<char> oper;
stack<double> data;
str += "$";
oper.push('#');
while(index < str.size()){
if(str[index]==' '){
index++;
}else if(isdigit(str[index])){
data.push(GetNumber(str,index));//注意这里不用自增,在函数中已经自增
}else{
if(Priority(str[index])>Priority(oper.top())){
oper.push(str[index++]);
}else{
double y = data.top();
data.pop();
double x = data.top();
data.pop();
data.push(Calculate(x,y,oper.top()));
oper.pop();
}
}
}
printf("%.2f\n",data.top());
}
return 0;
}