P1449 字尾表示式題解
阿新 • • 發佈:2021-07-29
#include <bits/stdc++.h> using namespace std; //字尾表示式 stack<int> n; int s, x, y; /** .是每個數字的結束標誌 @是整個表示式的結束標誌 測試用例 : 3.5.2.-*7.+@ 3*(5–2)+7 16 */ int main() { char ch; do { //(1)上來就讀入,讀完了再看是不是結束符,就是幹了再說~ ch = getchar(); //(2)讀入字元的辦法 if (ch >= '0' && ch <= '9') s = s * 10 + ch - '0'; //(3)按字元讀入轉為數字的辦法 else if (ch == '.') //表示數字結束 n.push(s), s = 0; //入棧,重新計數 else if (ch != '@') { //操作符 x = n.top(); n.pop(); y = n.top(); n.pop(); switch (ch) { case '+': n.push(y + x); break; case '-': n.push(y - x); //注意順序 break; case '*': n.push(y * x); break; case '/': n.push(y / x); //注意順序 break; } } } while (ch != '@'); printf("%d\n", n.top()); return 0; }