REM. Test of expression evaluator
*KEY 1 2^3*2^3+4|M
*KEY 2 1-2-3-4-5-6|M
*KEY 3 1/2/3/4/5/6|M
*KEY 4 1+2-3*4/5^6/7*8-9+10|M
*KEY 5 1^2/3*4-5+6-7*8/9^10|M
*KEY 6 2^3*2+4|M
*KEY 7 1+2^3*4|M
*KEY 8 3.14159|M
*KEY 9 -5^2|M
COLOUR 5
PRINT '"Use function keys for preset expressions"'
COLOUR 0
REPEAT
INPUT "Enter a numeric expression (+,-,*,/,^ operators only): "E$
ok% = TRUE
ON ERROR LOCAL PRINT 'REPORT$ : ok% = FALSE
IF ok% THEN
result1 = EVAL(E$)
PRINT "BASIC's evaluator gives: ";result1
op% = 0 : pr% = 1
result2 = FNeval(E$, op%, pr%, 99)
PRINT "Test evaluator gives: ";result2
IF result1 <> result2 COLOUR 1 : PRINT "ERROR!!!!" : COLOUR 0 : VDU 7
ENDIF
RESTORE ERROR
UNTIL FALSE
DEF FNeval(RETURN E$, RETURN O%, RETURN o%, ecxedx)
LOCAL p%(), P%, p%, eaxebx
DIM p%(5)
p%() = 0,1,1,2,2,3
REPEAT
P% = O%
p% = o%
eaxebx = ecxedx
ecxedx = VAL(E$)
REPEAT
E$ = MID$(E$,2)
O% = INSTR("+-*/^", LEFT$(E$,1))
UNTIL O%<>0 OR E$=""
E$ = MID$(E$,2) : REM Skip past operator
o% = p%(O%)
WHILE o% > p% ecxedx = FNeval(E$, O%, o%, ecxedx) : ENDWHILE
SWAP eaxebx,ecxedx
CASE P% OF
WHEN 0: ecxedx = eaxebx
WHEN 1: ecxedx += eaxebx
WHEN 2: ecxedx -= eaxebx
WHEN 3: ecxedx *= eaxebx
WHEN 4: ecxedx /= eaxebx
WHEN 5: ecxedx = ecxedx^eaxebx
ENDCASE
UNTIL o% < p%
= ecxedx ' Test of expression evaluator
!*KEY 1 2^3*2^3+4|M
!*KEY 2 1-2-3-4-5-6|M
!*KEY 3 1/2/3/4/5/6|M
!*KEY 4 1+2-3*4/5^6/7*8-9+10|M
!*KEY 5 1^2/3*4-5+6-7*8/9^10|M
!*KEY 6 2^3*2+4|M
!*KEY 7 1+2^3*4|M
!*KEY 8 3.14159|M
!*KEY 9 -5^2|M
print "Use function keys for preset expressions"
print
do
input "Enter a numeric expression (+,-,*,/,^ operators only): "; E$
result1 = eval(E$)
print "BASIC's evaluator gives: ";result1
op = 0 : pr = 1
result2 = evaluate(E$, op, pr, 99)
print "Test evaluator gives: ";result2
if result1 <> result2 then print "ERROR!!!!"
loop until 0
function evaluate(byref E$, byref O, byref o, ecxedx)
dim p(5)
p(1) = 1 : p(2) = 1 : p(3) = 2 : p(4) = 2 : p(5) = 3
do
P = O
p = o
eaxebx = ecxedx
ecxedx = val(E$)
do
E$ = mid$(E$,2)
O = instr("+-*/^", left$(E$,1))
loop until O<>0 or E$=""
E$ = mid$(E$,2) ' Skip past operator
o = p(O)
while o > p : ecxedx = evaluate(E$, O, o, ecxedx) : wend
temp = eaxebx : eaxebx = ecxedx : ecxedx = temp
select case P
case 0: ecxedx = eaxebx
case 1: ecxedx = ecxedx + eaxebx
case 2: ecxedx = ecxedx - eaxebx
case 3: ecxedx = ecxedx * eaxebx
case 4: ecxedx = ecxedx / eaxebx
case 5: ecxedx = ecxedx^eaxebx
end select
loop until o < p
evaluate = ecxedx
end function