谁有pascal用栈实现的表达是求值的程序代码?请给我一下,谢谢~
谁有pascal用栈实现的表达是求值的程序代码?请给我一下,谢谢~ 计算表达式的值 have a look 刚给你写的,感觉写的好长,为啥我的代码总是那么长?program exp_reduced;
const
inf='bds.in';
outf='bds.out';
maxn=100;
tr='+-*/()#';
var
amount,numtop,optop:integer;
bds:array[1..maxn] of string;
stacknum:array[1..maxn] of integer;
stackop:array[1..maxn] of string;
procedure init;
var i,j:integer;temp:string;
begin
readln(temp);
temp:=temp+'#';
amount:=0;
i:=1;j:=0;
while i<=length(temp) do
begin
j:=0;
if pos(temp[i],tr)<>0 then
begin
inc(amount);
bds[amount]:=temp[i];
inc(i);j:=i;
continue;
end;
inc(j);
while pos(temp[i+j],tr)=0 do inc(j);
inc(amount);
bds[amount]:=copy(temp,i,j);
inc(i,j);
end;
end;
procedure popnum;
begin
dec(numtop);
end;
procedure popop;
begin
dec(optop);
end;
procedure pushnum(v:integer);
begin
inc(numtop);
stacknum[numtop]:=v;
end;
procedure pushop(v:string);
begin
inc(optop);
stackop[optop]:=v;
end;
function judge(v:string):char;
var temp:string;
begin
temp:=stackop[optop];
if temp='#' then begin judge:='<';exit; end;
if temp='(' then
begin
if v=')' then begin judge:='='; exit; end
else begin judge:='<'; exit; end;
end;
if temp=')' then begin judge:='>'; exit;end;
if (temp='+') or (temp='-') then
begin
if (v='*') or (v='/') or (v='(') then begin judge:='<'; exit; end;
if (v=')') or (v='+') or (v='-') or (v='#') then begin judge:='>'; exit; end;
end;
if (temp='*') or (temp='/') then
begin
if (v='+') or (v='-') or (v=')') or (v='#') then begin judge:='>'; exit; end;
if (v='*') or (v='*') or (v='(') then begin judge:='<'; exit; end;
end;
end;
function operate(v1,v2:integer;op:string):integer;
begin
if op='+' then operate:=v1+v2
else if op='-' then operate:=v1-v2
else if op='*' then operate:=v1*v2
else if op='/' then operate:=trunc(v1/v2);
end;
procedure main;
var i,j,temp,wzy,a,b:integer;op:string;
begin
optop:=0;numtop:=0;
pushop('#');
i:=1;
while not ((bds[i]='#') and (stackop[optop]='#')) do
begin
if pos(bds[i],tr)=0 then
begin
val(bds[i],temp,wzy);
pushnum(temp);
inc(i);
end
else
begin
case judge(bds[i]) of
'<': //操作符栈顶元素优先级小于当前操作符优先级,将当前操作符入栈}
begin
pushop(bds[i]);
inc(i);
end;
'=': //操作符栈顶元素优先级等于当前操作符优先级,将操作符栈栈顶操作符出栈}
begin
popop;
inc(i);
end;
'>': //操作符栈顶元素优先级大于当前操作符优先级,
begin //将操作数栈顶两个运算数出栈,将操作符栈顶操作符出栈
a:=stacknum[numtop]; //计算,并将结果入操作数栈
popnum;
b:=stacknum[numtop];
popnum;
op:=stackop[optop];
popop;
pushnum(operate(b,a,op));
end;
end;
end;
end;
writeln(stacknum[1]);
end;
begin
assign(input,inf);
assign(output,outf);
reset(input);
rewrite(output);
init;
main;
close(input);
close(output);
end.
页:
[1]