上节实现了计算器的界面,这节实现核心算法,下节实现用户界面与业务逻辑的分离
目录
分离算法:将中缀表达式进行数字和运算符的分离
中缀转后缀算法:将中缀表达式转换为后缀表达式
后缀表达式计算 :通过后缀表达式计算最终结果
1、分离算法
思想:以符号作为标志对表达式中的字符逐个访问
- 初始累计变量num为空,遍历字符串每个字符
- 若遇到数字或小数点(即当前符号是数字的一部分),累加到num变量,并用pre变量记录当前符号(用来判断正负号)
- 若遇到其它符号(+, -, *, / , ( , ) ,+, -)
✔ 先看num变量,若有值,num的值放入队列,清空num
✔ 若为正负号,累计到num变量(流程能走到这说明num无值)
✔ 否则当前字符(即运算符或括号)入队列
✔ pre记录当前字符
- 遍历结束后若num不为空,入队列(遍历的最后一个字符是数字还没机会入队列)
区分正负号和加减号准则:正负号 + 和 - 在表达式的第一个位置、括号后的 + 和 - 、运算符后的 + 和 -
bool QCalculatorDec::isDigitOrDot(QChar c)
{
return (('0' <= c) && (c <= '9')) || (c == '.');
}
bool QCalculatorDec::isSymbol(QChar c)
{
return isOperator(c) || (c == '(') || (c == ')');
}
bool QCalculatorDec::isSign(QChar c)
{
return (c == '+') || (c == '-');
}
bool QCalculatorDec::isNumber(QString s)
{
bool ret = false;
s.toDouble(&ret);
return ret;
}
bool QCalculatorDec::isOperator(QString s)
{
return (s == "+") || (s == "-") || (s == "*") || (s == "/");
}
bool QCalculatorDec::isLeft(QString s)
{
return (s == "(");
}
bool QCalculatorDec::isRight(QString s)
{
return (s == ")");
}
int QCalculatorDec::priority(QString s)
{
int ret = 0; // 其他符号的优先级最低
if( (s == "+") || (s == "-") )
{
ret = 1;
}
if( (s == "*") || (s == "/") )
{
ret = 2;
}
return ret;
}
QQueue<QString> QCalculatorDec::split(const QString& exp)
{
QQueue<QString> ret;
QString num = "";
QString pre = "";
for(int i=0; i<exp.length(); i++)
{
if( isDigitOrDot(exp[i]) )
{
num += exp[i];
pre = exp[i];
}
else if( isSymbol(exp[i]) )
{
if( !num.isEmpty() )
{
ret.enqueue(num);
num.clear();
}
if( isSign(exp[i]) && ((pre == "") || (pre == "(") || isOperator(pre)) )
{
num += exp[i];
}
else
{
ret.enqueue(exp[i]);
}
pre = exp[i];
}
}
if( !num.isEmpty() )
{
ret.enqueue(num);
}
return ret;
}
2、括号匹配算法
合法的四则运算表达式中 ,括号匹配成对出现 ,左括号必然先于右括号出现
bool QCalculatorDec::match(QQueue<QString>& exp)
{
bool ret = true;
int len = exp.length();
QStack<QString> stack;
for(int i=0; i<len; i++)
{
if( isLeft(exp[i]) )
{
stack.push(exp[i]);
}
else if( isRight(exp[i]) )
{
if( !stack.isEmpty() && isLeft(stack.top()) )
{
stack.pop();
}
else
{
ret = false;
break;
}
}
}
return ret && stack.isEmpty();
}
3、中缀转后缀算法
中缀表达式:9.3 + ( 3 - -0.11 ) * 5 + 10
后缀表达式:9.3 3 -0.11 - 5 * 10 + +
流程:
- 9.3 为数字,直接输出
- + 为运算符且栈为空,入栈
- ( 为左括号,入栈
- 3是数字,直接输出
- - 是运算符,大于栈顶优先级,入栈
- -0.11 是数字,直接输出
- ) 为右括号,不断弹出栈顶,直到遇到左括号与当前的右括号匹配
- * 为运算符,大于栈顶优先级,入栈(后缀的表现形式为 num1 num2 op, 运算符始终在最后,当前的运算符优先级高, 先参与计算 )
- 5 为数字,直接输出
- + 为运算符,小于栈顶优先级,栈顶出栈输出,+入栈(后缀的表现形式为 num1 num2 op, 运算符始终在最后,当前的运算符优先级低, 后参与计算 )
- 10是数字,直接输出
- 此时栈不为空,全部输出
验证:从左到右分别将操作符的左边的两个数字与操作符进行运算
转换过程:
- 当前元素e为数字,输出到队列
- 当前元素e为运算符: 先与栈顶运算符进行优先级比较
✔ 小于等于:将栈顶元素输出到队列
✔ 将当前元素e入栈
- 当前元素e为左括号:入栈
- 当前元素e为右括号:
1. 弹出栈顶元素并输出到队列,直至栈顶元素为左括号
2. 将栈顶的左括号从栈中弹出
bool QCalculatorDec::transform(QQueue<QString>& exp, QQueue<QString>& output)
{
bool ret = match(exp);
QStack<QString> stack;
output.clear();
while( ret && !exp.isEmpty() )
{
QString e = exp.dequeue();
if( isNumber(e) )
{
output.enqueue(e);
}
else if( isOperator(e) )
{
while( !stack.isEmpty() && (priority(e) <= priority(stack.top())) )
{
output.enqueue(stack.pop());
}
stack.push(e);
}
else if( isLeft(e) )
{
stack.push(e);
}
else if( isRight(e) )
{
while( !stack.isEmpty() && !isLeft(stack.top()) )
{
output.enqueue(stack.pop());
}
if( !stack.isEmpty() )
{
stack.pop();
}
}
else
{
ret = false;
}
}
while( !stack.isEmpty() )
{
output.enqueue(stack.pop());
}
if( !ret )
{
output.clear();
}
return ret;
}
4、后缀表达式计算
遍历后缀表达式中的数字和运算符
- 当前元素为数字,进栈
- 当前元素为运算符:
1. 从栈中弹出右操作数
2. 从栈中弹出左操作数
3. 根据符号进行运算
4 将运算结果压入栈中
遍历结束
- 栈中的唯一数字为运算结果
QString QCalculatorDec::calculate(QString l, QString op, QString r)
{
QString ret = "Error";
if( isNumber(l) && isNumber(r) )
{
double lp = l.toDouble();
double rp = r.toDouble();
if( op == "+" )
{
ret.sprintf("%f", lp + rp);
}
else if( op == "-" )
{
ret.sprintf("%f", lp - rp);
}
else if( op == "*" )
{
ret.sprintf("%f", lp * rp);
}
else if( op == "/" )
{
const double P = 0.000000000000001;
if( (-P < rp) && (rp < P) )
{
ret = "Error";
}
else
{
ret.sprintf("%f", lp / rp);
}
}
else
{
ret = "Error";
}
}
return ret;
}
QString QCalculatorDec::calculate(QQueue<QString>& exp)
{
QString ret = "Error";
QStack<QString> stack;
while( !exp.isEmpty() )
{
QString e = exp.dequeue();
if( isNumber(e) )
{
stack.push(e);
}
else if( isOperator(e) )
{
QString rp = !stack.isEmpty() ? stack.pop() : "";
QString lp = !stack.isEmpty() ? stack.pop() : "";
QString result = calculate(lp, e, rp);
if( result != "Error" )
{
stack.push(result);
}
else
{
break;
}
}
else
{
break;
}
}
if( exp.isEmpty() && (stack.size() == 1) && isNumber(stack.top()) )
{
ret = stack.pop();
}
return ret;
}
5、完整代码
QCalculatorDec.h
#ifndef _CALCULATORCORE_H_
#define _CALCULATORCORE_H_
#include <QString>
#include <QStack>
#include <QQueue>
class QCalculatorDec
{
protected:
QString m_exp;
QString m_result;
bool isDigitOrDot(QChar c);
bool isSymbol(QChar c);
bool isSign(QChar c);
bool isNumber(QString s);
bool isOperator(QString s);
bool isLeft(QString s);
bool isRight(QString s);
int priority(QString s);
bool match(QQueue<QString>& exp);
QString calculate(QQueue<QString>& exp);
QString calculate(QString l, QString op, QString r);
bool transform(QQueue<QString>& exp, QQueue<QString>& output);
QQueue<QString> split(const QString& exp);
public:
QCalculatorDec();
~QCalculatorDec();
bool expression(const QString& exp);
QString expression();
QString result();
};
#endif
QCalculatorDec.cpp
#include "QCalculatorDec.h"
QCalculatorDec::QCalculatorDec()
{
m_exp = "";
m_result = "";
}
QCalculatorDec::~QCalculatorDec()
{
}
bool QCalculatorDec::isDigitOrDot(QChar c)
{
return (('0' <= c) && (c <= '9')) || (c == '.');
}
bool QCalculatorDec::isSymbol(QChar c)
{
return isOperator(c) || (c == '(') || (c == ')');
}
bool QCalculatorDec::isSign(QChar c)
{
return (c == '+') || (c == '-');
}
bool QCalculatorDec::isNumber(QString s)
{
bool ret = false;
s.toDouble(&ret);
return ret;
}
bool QCalculatorDec::isOperator(QString s)
{
return (s == "+") || (s == "-") || (s == "*") || (s == "/");
}
bool QCalculatorDec::isLeft(QString s)
{
return (s == "(");
}
bool QCalculatorDec::isRight(QString s)
{
return (s == ")");
}
int QCalculatorDec::priority(QString s)
{
int ret = 0;
if( (s == "+") || (s == "-") )
{
ret = 1;
}
if( (s == "*") || (s == "/") )
{
ret = 2;
}
return ret;
}
bool QCalculatorDec::expression(const QString& exp)
{
bool ret = false;
QQueue<QString> spExp = split(exp);
QQueue<QString> postExp;
m_exp = exp;
if( transform(spExp, postExp) )
{
m_result = calculate(postExp);
ret = (m_result != "Error");
}
else
{
m_result = "Error";
}
return ret;
}
QString QCalculatorDec::result()
{
return m_result;
}
QQueue<QString> QCalculatorDec::split(const QString& exp)
{
QQueue<QString> ret;
QString num = "";
QString pre = "";
for(int i=0; i<exp.length(); i++)
{
if( isDigitOrDot(exp[i]) )
{
num += exp[i];
pre = exp[i];
}
else if( isSymbol(exp[i]) )
{
if( !num.isEmpty() )
{
ret.enqueue(num);
num.clear();
}
if( isSign(exp[i]) && ((pre == "") || (pre == "(") || isOperator(pre)) )
{
num += exp[i];
}
else
{
ret.enqueue(exp[i]);
}
pre = exp[i];
}
}
if( !num.isEmpty() )
{
ret.enqueue(num);
}
return ret;
}
bool QCalculatorDec::match(QQueue<QString>& exp)
{
bool ret = true;
int len = exp.length();
QStack<QString> stack;
for(int i=0; i<len; i++)
{
if( isLeft(exp[i]) )
{
stack.push(exp[i]);
}
else if( isRight(exp[i]) )
{
if( !stack.isEmpty() && isLeft(stack.top()) )
{
stack.pop();
}
else
{
ret = false;
break;
}
}
}
return ret && stack.isEmpty();
}
bool QCalculatorDec::transform(QQueue<QString>& exp, QQueue<QString>& output)
{
bool ret = match(exp);
QStack<QString> stack;
output.clear();
while( ret && !exp.isEmpty() )
{
QString e = exp.dequeue();
if( isNumber(e) )
{
output.enqueue(e);
}
else if( isOperator(e) )
{
while( !stack.isEmpty() && (priority(e) <= priority(stack.top())) )
{
output.enqueue(stack.pop());
}
stack.push(e);
}
else if( isLeft(e) )
{
stack.push(e);
}
else if( isRight(e) )
{
while( !stack.isEmpty() && !isLeft(stack.top()) )
{
output.enqueue(stack.pop());
}
if( !stack.isEmpty() )
{
stack.pop();
}
}
else
{
ret = false;
}
}
while( !stack.isEmpty() )
{
output.enqueue(stack.pop());
}
if( !ret )
{
output.clear();
}
return ret;
}
QString QCalculatorDec::calculate(QString l, QString op, QString r)
{
QString ret = "Error";
if( isNumber(l) && isNumber(r) )
{
double lp = l.toDouble();
double rp = r.toDouble();
if( op == "+" )
{
ret.sprintf("%f", lp + rp);
}
else if( op == "-" )
{
ret.sprintf("%f", lp - rp);
}
else if( op == "*" )
{
ret.sprintf("%f", lp * rp);
}
else if( op == "/" )
{
const double P = 0.000000000000001;
if( (-P < rp) && (rp < P) )
{
ret = "Error";
}
else
{
ret.sprintf("%f", lp / rp);
}
}
else
{
ret = "Error";
}
}
return ret;
}
QString QCalculatorDec::calculate(QQueue<QString>& exp)
{
QString ret = "Error";
QStack<QString> stack;
while( !exp.isEmpty() )
{
QString e = exp.dequeue();
if( isNumber(e) )
{
stack.push(e);
}
else if( isOperator(e) )
{
QString rp = !stack.isEmpty() ? stack.pop() : "";
QString lp = !stack.isEmpty() ? stack.pop() : "";
QString result = calculate(lp, e, rp);
if( result != "Error" )
{
stack.push(result);
}
else
{
break;
}
}
else
{
break;
}
}
if( exp.isEmpty() && (stack.size() == 1) && isNumber(stack.top()) )
{
ret = stack.pop();
}
return ret;
}
main.cpp
#include <QtGui/QApplication>
#include "QCalculatorDec.h"
#include <QDebug>
int main(int argc, char *argv[])
{
QCalculatorDec c;
c.expression(" (5 - 8) * (5 - 6) ");
qDebug() << c.result();
return 0;
}