to all:
我这几天发信不太好:直接贴这里吧, 不长:
做的是 console.
{Expression.dpr}
program Expression;
uses
SysUtils;
var
Input: string;
function Translate(s: string): string;
var
Stack: array of char;
i, Top: Integer;
temp: string;
begin
SetLength(Stack, Length(s));
i := 1;
Top := 0;
temp := '';
while i <= Length(s) do
begin
case s of
'0'..'9':
begin
while (i <= Length(s)) and (s in ['0'..'9', '.']) do
begin
temp := temp + s;
Inc(i);
end;
temp := temp + ' ';
Dec(i);
end;
'+', '-':
begin
while (Top > 0) and (Stack[Top - 1] <> '(') do
begin
temp := temp + Stack[Top - 1];
Dec(Top);
end;
Stack[Top] := s;
Inc(Top);
end;
'*', '/':
begin
if (Top > 0) and ((Stack[Top - 1] = '*') or (Stack[Top - 1] = '/'))
then
begin
temp := temp + Stack[Top - 1];
Dec(Top);
end;
Stack[Top] := s;
Inc(Top);
end;
'(':
begin
Stack[Top] := s;
Inc(Top);
end;
')':
begin
while (Stack[Top - 1] <> '(') and (Top > 0) do
begin
temp := temp + Stack[Top - 1];
Dec(Top);
end;
if Top = 0 then
begin
temp := '''('' expected!';
Top := 0;
Break;
end;
Dec(Top);
end;
end;
Inc(i);
end;
while (Top > 0) do
begin
if Stack[Top - 1] = '(' then
begin
temp := ''')'' expected1';
Break;
end;
Temp := Temp + Stack[Top - 1];
Dec(Top);
end;
Result := temp;
end;
procedure Caculate(s: string);
var
Stack: array of real;
i, Top: Integer;
Info, temp: string;
HasDot: boolean;
begin
SetLength(stack, Length(s));
i := 1;
Top := -1;
Info := '';
while i <= Length(s) do
begin
case s of
'+', '-', '/', '*':
begin
if Top = 0 then
begin
Info := 'Operant Expected!';
break;
end;
case s of
'+': Stack[Top - 1] := Stack[Top - 1] + Stack[Top];
'-': Stack[Top - 1] := Stack[Top - 1] - Stack[Top];
'*': Stack[Top - 1] := Stack[Top - 1] * Stack[Top];
'/': Stack[Top - 1] := Stack[Top - 1] / Stack[Top];
end;
Dec(Top);
end;
'0'..'9':
begin
temp := '';
HasDot := False;
while (i <= Length(s)) and (s in ['0'..'9', '.']) do
begin
temp := temp + s;
if s = '.' then
if not HasDot then
HasDot := True
else
begin
Info := 'Number Invalidate!';
Break;
end;
Inc(i);
end;
Inc(Top);
if HasDot then
Stack[Top] := StrToFloat(temp)
else
Stack[Top] := StrToInt(temp);
Dec(i);
end;
end;
Inc(i);
end;
if Top > 0 then
Info := 'Opcode Expected!';
Writeln(Format('%f', [Stack[Top]]));
end;
begin
writeln('Please input the expression:');
readln(Input);
Caculate(Translate(Input));
readln;
end.