#include #include using namespace std;

int main() { string postfix; cin >> postfix; // 输入后缀式 stack s; // 定义一个栈用于存储数字 int result; // 定义一个变量用于存储结果 for (char c : postfix) { if (isdigit(c)) { // 如果是数字,压入栈中 s.push(c - '0'); } else { // 如果是运算符,弹出栈顶的两个数字进行运算 int num2 = s.top(); s.pop(); int num1 = s.top(); s.pop(); switch (c) { // 根据运算符计算结果,并压入栈中 case '+': s.push(num1 + num2); break; case '-': s.push(num1 - num2); break; case '*': s.push(num1 * num2); break; case '/': s.push(num1 / num2); break; } } } result = s.top(); // 最后栈顶就是结果 cout << result << endl; // 输出结果 return 0;

1输入一个标准后缀式保证每个运算数 都是一位数输出其结果。输入12+输出3输入321-9231+-+输出4 cpp code

原文地址: https://www.cveoy.top/t/topic/fyVV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录