function TermToFloat(
Const Term:
string):real;
function _Eval(term:
string;
var i: Integer): Integer;
const
isNone = 0;
isNum = 1;
isOp = 2;
var
numStack:
array[0..10]
of Double;
number, code, sign, sp, j, decimal: Double;
Ops:
string;
c: Char;
function OpOrder(c: Char): Integer;
begin
if c = '
$'
then
Result := -1
else
Result := (Pos(c, '
+-*/') + 1)
div 2;
end;
begin
fillchar(numstack, sizeof(numstack), 0);
sign := 1;
Ops := '
$';
SP := 0;
number := 0;
Result := 0;
code := isNone;
while i < length(term)
do begin
inc(i);
c := term[i];
case c
of
'
0'..'
9':
begin
if decimal>0
then begin
number := (number + ord(c) - 48)/decimal;
decimal := decimal*10;
end
else
number := 10 * number + ord(c) - 48;
code := isNum;
end;
'
.':
if decimal>0
then
raise Exception.Create('
invalid decimal')
else
decimal := 10;
'
(':
begin
decimal := 0;
number := _Eval(term, i);
code := isNum;
end;
'
':
begin
decimal := 0;
continue;
end;
'
+', '
-', '
*', '
/', '
)':
begin
decimal := 0;
if code = isNum
then begin
numStack[SP] := sign * number;
// Hier kommt der Fehler (s.u.)
sign := 1;
inc(SP);
number := 0;
end else if code = isOp
then begin
if c = '
-'
then
sign := -sign;
Continue
end;
code := isop;
if Length(Ops) > 1
then begin
while opOrder(c) <= OpOrder(Ops[Length(Ops)])
do begin
dec(sp);
case Ops[Length(Ops)]
of
'
*': numstack[sp - 1] := numstack[sp - 1] * numstack[sp];
'
/': numstack[sp - 1] := numstack[sp - 1]
div numstack[sp];
'
+': numstack[sp - 1] := numstack[sp - 1] + numstack[sp];
'
-': numstack[sp - 1] := numstack[sp - 1] - numstack[sp];
end;
numStack[sp] := 0;
setLength(Ops, length(Ops) - 1);
end;
end;
Ops := Ops + c;
if c = '
)'
then begin
number := NumStack[0];
break;
end;
end;
end;
end;
result := Number;
end;
var
i: Integer;
begin
i := 0;
Result := _Eval('
(' + term + '
)', i);
end;