编程题-计算表达式
给一个带 加减乘除符号、小数、不包含括号 的表达式,求值
利用双栈模拟后缀表达式计算
#include <string> #include <stack> #include <stdlib.h> #include<iostream> using namespace std; bool priorCompare(char a, char b) { if (a == '\0') return false; if (a == '*' || a == '/') { if (b == '*' || b == '/') return false; else return true; } return false; } double getCalc(double a, double b, char sign) { if (sign == '*')return a * b; else if (sign == '/') return a / b; else if (sign == '+') return a + b; else return a - b; } double compute(string input) { stack<char> sign; stack<double> result; string digits = ""; // 注意这里是字符长度+1的循环,用于处理收尾数字,不能写成增强for for (int i = 0; i <= input.size();i++) { char ch = input[i]; if (isdigit(ch) || ch == '.') digits += ch; else { result.push(atof(digits.c_str())); digits = ""; // 如果当前运算符优先级低于栈顶元素则计算,并压栈,循环直到当前运算符优先级大于栈顶 while (!sign.empty() && !priorCompare(ch, sign.top())) { double b = result.top(); result.pop(); double a = result.top(); result.pop(); result.push(getCalc(a, b, sign.top())); sign.pop(); } sign.push(ch); } } return result.top(); } int main() { cout << compute("1.5+3*4/2") << endl; cout << compute("1.5+3*4+4/2-1") << endl; }
本文作者:YaosGHC
本文链接:https://www.cnblogs.com/yaocy/p/17207887.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步