做普通网站公司吗甘肃seo技术
L2-1 简单计算器 (25分)【36行代码搞定栈出入问题】
前言:
如果熟悉STL的stack
,这道题算是一道水题吧
题目:
本题要求你为初学数据结构的小伙伴设计一款简单的利用堆栈执行的计算器。如上图所示,计算器由两个堆栈组成,一个堆栈 S1存放数字,另一个堆栈 S2存放运算符。计算器的最下方有一个等号键,每次按下这个键,计算器就执行以下操作:
Sample Input:
5
40 5 8 3 2
/ * - +
Sample Output:
2
Sample Input:
5
2 5 8 4 4
* / - +
Sample Output:
ERROR: 5/0
AC代码:
#include "bits/stdc++.h" // 万用头文件
using namespace std;int calculate(int a, int b, char c) {if (c=='+')return a+b;if (c=='-')return b-a;if (c=='*')return a*b;if (c=='/')return b/a;
}int main(){int n; cin>>n;stack<int>digit;stack<char>op;// inputfor (int i = 0; i < n; ++i) {int temp; cin>>temp;digit.push(temp);}for (int i = 0; i < n - 1; ++i) {char temp;cin>>temp;op.push(temp);}// dealwhile (digit.size()!=1){int a = digit.top(); digit.pop();int b = digit.top(); digit.pop();char c = op.top(); op.pop();if (a==0 && c=='/'){cout<<"ERROR: "<<b<<"/"<<a<<endl;return 0;}digit.push(calculate(a,b,c));}cout<<digit.top()<<endl;
}