栈3--后缀表达式

栈3--后缀表达式

一、心得

 代码的关键部分标红

二、题目及分析

 后缀表达式

不包含括号,运算符放在两个运算对象的后面,所有的计算按运算符出现的顺序,严格从左向右进行(不再考虑运算符的优先规则,如:(2 + 1) * 3 , 即2 1 + 3 *

三、代码及结果

 1 #include <iostream>
 2 #include <stack>
 3 #include <string>
 4 using namespace std;
 5 
 6 stack<double> sta; 
 7 
 8 int cal(string &s){
 9     for(int i=0;i<s.length();i++){
10         if(s[i]=='+'){
11             double b=sta.top();
12             sta.pop();
13             double a=sta.top();
14             sta.pop();
15             sta.push(a+b);
16             //cout<<a+b<<endl;
17         } 
18         else if(s[i]=='-'){
19             double b=sta.top();
20             sta.pop();
21             double a=sta.top();
22             sta.pop();
23             sta.push(a-b);
24             //cout<<a-b<<endl;
25         } 
26         else if(s[i]=='*'){
27             double b=sta.top();
28             sta.pop();
29             double a=sta.top();
30             sta.pop();
31             sta.push(a*b);
32             //cout<<a*b<<endl;
33         } 
34         else if(s[i]=='/'){
35             double b=sta.top();
36             sta.pop();
37             double a=sta.top();
38             sta.pop();
39             sta.push(a/b);
40             //cout<<a/b<<endl;
41         } 
42         else {
43             //主要是这一部分要看看  
44             double x=0;
45             while(s[i]!=' '){
46                 x=x*10+s[i++]-'0';
47             } 
48             sta.push(x);
49             //cout<<x<<endl;
50         }
51     }
52     return sta.top();
53 }
54 
55 int main(){
56     freopen("in.txt","r",stdin);
57     string s;
58     getline(cin,s);
59     cout<<cal(s)<<endl;
60     return 0;
61 } 

16 9 4 3 +*-

原文地址:https://www.cnblogs.com/Renyi-Fan/p/7140344.html