本文使用C++实现Shunting-yard算法,将中缀表达式转换为后缀表达式,然后使用后缀表达式计算结果,实现了目前支持以下
- 四则运算(+、-、*、/)
- 开平方(^)
- 取基数为 10 的对数(L)
- 小括号
的组合,实现代码如下
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <cctype>
#include <math.h>
/**
* @brief getPrecedence 判断优先级
* @param op 操作符
* @return 0是特殊的,最高优先级,其他的数字越大,优先级越高
*/
int getPrecedence(char op) {
if (op == '+' || op == '-') {
return 1;
}
else if (op == '*' || op == '/') {
return 2;
}
else if (op == '^')
{
return 3;
}
else {
return 0;
}
}
/**
* @brief isOperator 判断字符是否是运算符
* @param c
* @return 是返回true
*/
bool isOperator(char c