PTA简单计算器

一、题目描述

 

 二、解题思路

  这题设计两个栈就可以做出来了,属于简单数据结构的应用,判断一下除零的情况即可

三、代码实现

 1 #include "bits/stdc++.h"
 2 using namespace std;
 3 stack <int> s1;
 4 stack <char> s2;
 5 int main()
 6 {
 7     int n;
 8     cin >> n;
 9     int a;
10     char ch;
11     for(int i = 1;i <= n;i++){
12         cin >> a;
13         s1.push(a);
14     }
15     for(int i = 1;i <= n - 1;i++){
16         cin >> ch;
17         s2.push(ch);
18     }
19     bool ok = true;
20     while(!s1.empty() && !s2.empty()){
21         int np1;
22         int np2;
23         np1 = s1.top();
24         s1.pop();
25         np2 = s1.top();
26         s1.pop();
27         ch = s2.top();
28         s2.pop();
29         int ans;
30         if(ch == '+')
31             ans = np1 + np2;
32         else if(ch == '-')
33             ans = np2 - np1;
34         else if(ch == '/'){
35             if(np1)
36                 ans = np2 / np1;
37             else{
38                 cout << "ERROR: "<< np2 << "/0" << endl;
39                 ok = false;
40                 break;
41             }
42         }
43         else
44              ans = np2 * np1;
45         s1.push(ans);
46     }
47     if(ok)
48         cout << int(s1.top()) << endl;
49     return 0;
50 }
posted @ 2022-03-19 15:14  scannerkk  阅读(326)  评论(0)    收藏  举报