47 lines
1.3 KiB
C++
47 lines
1.3 KiB
C++
#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;
|
||
} |