-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheval.pas
77 lines (68 loc) · 1.49 KB
/
eval.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
unit eval;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, StdCtrls;
function Eval(expression: string): variant;
implementation
function isOp(aSign: string): boolean;
begin
Result := False;
if aSign = '+' then
Result := True;
if aSign = '-' then
Result := True;
if aSign = '*' then
Result := True;
if aSign = '/' then
Result := True;
end;
function GetToken(expression: string; out Counter: integer): variant;
var
aChar: string;
sData: string;
begin
repeat
aChar := expression[Counter];
if aChar = ' ' then
aChar := '';
if isOp(aChar) then
break
else
begin
sData := sData + aChar;
Inc(Counter);
end;
until Counter > Length(expression);
Result := StrToFloat(sData);
end;
function Eval(expression: string): variant;
var
aChar: string;
aOperator: string;
Ret: variant;
iCount: integer;
begin
iCount := 1;
while iCount < Length(expression) do
begin
aChar := expression[iCount];
if isOp(aChar) then
begin
aOperator := Copy(expression, iCount, 1);
Inc(iCount);
end;
if aOperator = '' then
Ret := Trim(GetToken(expression, iCount));
if aOperator = '+' then
Ret := Ret + GetToken(expression, iCount);
if aOperator = '-' then
Ret := Ret - GetToken(expression, iCount);
if aOperator = '*' then
Ret := Ret * GetToken(expression, iCount);
if aOperator = '/' then
Ret := Ret / GetToken(expression, iCount);
end;
Result := Ret;
end;
end.