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 }
本文来自博客园,作者:{scanner},转载请注明原文链接:{https://home.cnblogs.com/u/scannerkk/}

浙公网安备 33010602011771号