Skip to content

Commit

Permalink
fix(core): make the % works correctly
Browse files Browse the repository at this point in the history
Just like KCalc and GNOME Calculator.

Closes linuxdeepin#12
  • Loading branch information
iovxw committed Sep 30, 2019
1 parent 6144a21 commit e330333
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
31 changes: 27 additions & 4 deletions core/evaluator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1314,10 +1314,9 @@ void Evaluator::compile(const Tokens& tokens)
m_codes.append(Opcode(Opcode::Fact));
break;
case Token::Percent:
syntaxStack.pop();
m_constants.append(HNumber("0.01"));
m_codes.append(Opcode(Opcode::Load, m_constants.count() - 1));
m_codes.append(Opcode(Opcode::Mul));
ruleFound = true;
syntaxStack.reduce(2);
m_codes.append(Opcode(Opcode::Pct));
break;
default:;
}
Expand Down Expand Up @@ -1924,6 +1923,27 @@ Quantity Evaluator::exec(const QVector<Opcode>& opcodes,
stack.push(val2);
break;

case Opcode::Pct:
if (stack.count() < 1) {
m_error = tr("invalid expression");
return CMath::nan();
}
val1 = stack.pop();

switch ((pc + 1) < opcodes.count() ?
opcodes.at(pc + 1).type : Opcode::Nop) {
case Opcode::Add:
case Opcode::Sub:
val2 = stack.pop();
stack.push(val2);
break;
default:
val2 = 1;
}
val1 = checkOperatorResult(val2 * (val1 * HNumber("0.01")));
stack.push(val1);
break;

case Opcode::Conv:
if (stack.count() < 2) {
m_error = tr("invalid expression");
Expand Down Expand Up @@ -2470,6 +2490,9 @@ QString Evaluator::dump()
case Opcode::BOr:
code = "BOr";
break;
case Opcode::Pct:
code = "Pct";
break;
default:
code = "Unknown";
break;
Expand Down
2 changes: 1 addition & 1 deletion core/opcode.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Opcode
{
public:
enum Type { Nop, Load, Ref, Function, Add, Sub, Neg, Mul, Div, Pow,
Fact, Modulo, IntDiv, LSh, RSh, BAnd, BOr, Conv };
Fact, Modulo, IntDiv, LSh, RSh, BAnd, BOr, Conv, Pct };

Type type;
unsigned index;
Expand Down

0 comments on commit e330333

Please sign in to comment.