[x] Evaluate a% with no preceding operator as (a / 100)
[x] Evaluate a + b% as a + (b*a/100)
[x] Evaluate a - b% as a - (b*a/100)
[x] Evaluate a * b% as a * (b * a / 100) (Google gives a * (b/100))
[x] Evaluate a / b% as a / (b * a / 100) (Google gives a / (b/100))
To fix this within the current paradigm (reverse Polish notation), % is treated as a special token and a new token representing the current left value (CLV) is introduced. The former is replaced during scanning with an expression involving * , /, 100 and the CLV except that special versions of the multiply and divide operators are used that have a higher than normal precedence in order to ensure the percentage calculation is performed first. During evaluation the CLV is obtained from the stack.
An advantage of this approach is that it correctly evaluates expressions such as (100 + 50) + (7 + 3)% as 165 whereas Google gives the incorrect answer 150.1.
However, it is unclear what the correct answer is for expressions such as a * b% and a / b%. The current solution gives different answers to Google for these expressions. For consistency, in this PR a * b% evaluates as a * (b * a / 100) and a / b% evaluates as a / (b*a / 100) i.e. the percentage is evaluated the same way regardless of the preceding operator.
Fixes #222
a%
with no preceding operator as(a / 100)
a + b%
asa + (b*a/100)
a - b%
asa - (b*a/100)
a * b%
asa * (b * a / 100)
(Google givesa * (b/100)
)a / b%
asa / (b * a / 100)
(Google givesa / (b/100)
)To fix this within the current paradigm (reverse Polish notation),
%
is treated as a special token and a new token representing the current left value (CLV) is introduced. The former is replaced during scanning with an expression involving*
,/
,100
and the CLV except that special versions of the multiply and divide operators are used that have a higher than normal precedence in order to ensure the percentage calculation is performed first. During evaluation the CLV is obtained from the stack.An advantage of this approach is that it correctly evaluates expressions such as
(100 + 50) + (7 + 3)%
as165
whereas Google gives the incorrect answer150.1
.However, it is unclear what the correct answer is for expressions such as
a * b%
anda / b%
. The current solution gives different answers to Google for these expressions. For consistency, in this PRa * b%
evaluates asa * (b * a / 100)
anda / b%
evaluates asa / (b*a / 100)
i.e. the percentage is evaluated the same way regardless of the preceding operator.