Cita:
Empezado por darkone2k3
Gracias roman por responder, voy a investigar lo que me dices.
Salu2 desde Chile.
|
Estimado, la función Eval para delphi es fácil, aquí va:
Código Delphi
[-]
function Eval(const expression : string) : extended;
var
pos : Integer;
ch : char;
function GetChar : char;
begin
if pos < Length (expression) then
begin
Inc (pos);
ch := expression [pos]
end
else ch := #0;
result := ch
end;
function GetNonWhitespace : char;
begin
repeat
GetChar
until not (ch in [' ', #9]);
result := ch
end;
function CalcAddition : extended; forward;
function CalcNumber : extended;
var
s : string;
gotPoint : boolean;
begin
gotPoint := False;
while ch in ['0'..'9'] do
begin
s := s + ch;
if (GetChar = '.') and not gotPoint then
begin
s := s + ch;
GetChar;
gotPoint := True
end
end;
result := StrToFloat (s)
end;
function CalcExpressionInBrackets : double;
begin
result := CalcAddition;
if ch = ')' then
GetChar
else
raise Exception.Create ('Missing '')'' in expression')
end;
function CalcTerm : extended;
begin
case ch of
'0'..'9' : result := CalcNumber;
'(' : result := CalcExpressionInBrackets;
else raise Exception.Create ('Syntax error in expression')
end
end;
function CalcSignedTerm : extended;
begin
case GetNonWhitespace of
'+' : result := CalcSignedTerm;
'-' : result := -CalcSignedTerm;
else result := CalcTerm
end
end;
function CalcPower : extended;
begin
result := CalcSignedTerm;
while ch = '^' do
result := exp (ln (result) * CalcSignedTerm)
end;
function CalcMultiplication : extended;
begin
result := CalcPower;
while ch in ['*', '/'] do
case ch of
'*' : result := result * CalcPower;
'/' : result := result / CalcPower
end
end;
function CalcAddition : extended;
begin
result := CalcMultiplication;
while ch in ['+', '-'] do
case ch of
'+' : result := result + CalcMultiplication;
'-' : result := result - CalcMultiplication
end
end;
begin
pos := 0;
result := CalcAddition
end;