求学长学姐解答,这一部分我没有学明白,请问如果求得下面公式的计算过程?
1条回答 默认 最新
- 夜枭龙 2023-04-16 01:49关注
以下是一个使用STL编写公式的示例代码:
#include <iostream> #include <string> #include <stack> using namespace std; int main() { string formula = "2*(3+4)/5-6"; stack<char> operators; stack<double> operands; for (char c : formula) { if (isdigit(c)) { operands.push(c - '0'); } else if (c == '(') { operators.push(c); } else if (c == ')') { while (operators.top() != '(') { char op = operators.top(); operators.pop(); double b = operands.top(); operands.pop(); double a = operands.top(); operands.pop(); if (op == '+') { operands.push(a + b); } else if (op == '-') { operands.push(a - b); } else if (op == '*') { operands.push(a * b); } else if (op == '/') { operands.push(a / b); } } operators.pop(); } else if (c == '+' || c == '-' || c == '*' || c == '/') { while (!operators.empty() && operators.top() != '(' && ((c == '+' || c == '-') ? 1 : 2) <= ((operators.top() == '+' || operators.top() == '-') ? 1 : 2)) { char op = operators.top(); operators.pop(); double b = operands.top(); operands.pop(); double a = operands.top(); operands.pop(); if (op == '+') { operands.push(a + b); } else if (op == '-') { operands.push(a - b); } else if (op == '*') { operands.push(a * b); } else if (op == '/') { operands.push(a / b); } } operators.push(c); } } while (!operators.empty()) { char op = operators.top(); operators.pop(); double b = operands.top(); operands.pop(); double a = operands.top(); operands.pop(); if (op == '+') { operands.push(a + b); } else if (op == '-') { operands.push(a - b); } else if (op == '*') { operands.push(a * b); } else if (op == '/') { operands.push(a / b); } } cout << formula << " = " << operands.top() << endl; return 0; }
```
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
- ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e
- ¥15 使用deepspeed训练,发现想要训练的参数没有梯度
- ¥15 寻找一块做为智能割草机的驱动板(标签-stm32|关键词-m3)
- ¥15 信息管理系统的查找和排序
- ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),怎么用读取的电磁传感器信号表示小车所在的位置
- ¥15 如何解决y_true和y_predict数据类型不匹配的问题(相关搜索:机器学习)
- ¥15 PB中矩阵文本型数据的总计问题。
- ¥15 MATLAB卫星二体模型仿真
- ¥15 怎么让数码管亮的同时让led执行流水灯代码