#include #include #include #include using namespace std;

int main() { string s; getline(cin, s); // 读入字符串 stack num; // 存储数字的栈 stack op; // 存储运算符的栈 int n = s.size(); int i = 0; while (i < n) { if (s[i] == ' ') { i++; continue; } if (isdigit(s[i])) { // 处理数字 int j = i; while (j < n && isdigit(s[j])) j++; int x = stoi(s.substr(i, j-i)); // 将字符串转为数字 num.push(x); i = j; } else { // 处理运算符 if (s[i] == '+' || s[i] == '-') { // 加减法 while (!op.empty() && (op.top() == '' || op.top() == '/')) { // 先计算乘除法 int b = num.top(); num.pop(); int a = num.top(); num.pop(); if (op.top() == '') num.push(a * b); else num.push(a / b); op.pop(); } op.push(s[i]); } else { // 乘除法 while (!op.empty() && (op.top() == '' || op.top() == '/')) { // 同级运算,先从左往右计算 int b = num.top(); num.pop(); int a = num.top(); num.pop(); if (op.top() == '') num.push(a * b); else num.push(a / b); op.pop(); } op.push(s[i]); } i++; } } while (!op.empty()) { // 处理栈中剩余的运算符 int b = num.top(); num.pop(); int a = num.top(); num.pop(); if (op.top() == '+') num.push(a + b); else if (op.top() == '-') num.push(a - b); else if (op.top() == '*') num.push(a * b); else num.push(a / b); op.pop(); } cout << num.top() << endl; return 0; }

编程实现:简单算术题计算器

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

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