高分求将中缀表达式转换为后缀表达式并求值,pascal.

bestycka 2011-05-15 02:24:53
题目是用栈将任意输入的表达式转换成后缀表达式,并求值。(输入中可能包含小数。)当时就没做出来,老师要我们下来做,下周三交,可是我做了三天还是没解决,水平太有限了,想向高手求助
急急。。。
...全文
347 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
wxykyfreedom 2012-04-15
  • 打赏
  • 举报
回复
小数也能算得!!
oj.jzxx.net上的1194题
wxykyfreedom 2012-04-15
  • 打赏
  • 举报
回复
var
str,str1,str2:string;
a,l,i,j,k,k1,l2,t,p:longint;
k2:integer;
b:array[1..1000] of real;
s:array[1..1000] of char;
tf,tfd,tfdd:boolean;
begin
readln(str1);
l:=length(str1);
p:=0;
tf:=false;
tfd:=false;
while i<=l do
begin
inc(i);
j:=i;
if ((str1[j-1]<'0') or (str1[j-1]>'9')) then
while ((str1[j]>='0') and (str1[j]<='9') and (j<=l)) or (str1[j]='.') do inc(j);
dec(j);
for k:=i to j do
if str1[k]='.' then
begin
for k1:=i to j do str:=str+str1[k1];
str:=str+' ';
tfd:=true;
end;
if tfd then begin tfd:=false;i:=j;continue; end;
case str1[i] of
'0'..'9':
begin
if (str1[i+1]<'0') or (str1[i+1]>'9') then
begin
if tf then
begin
a:=a*10+(ord(str1[i])-48);
while a<>0 do
begin
case a mod 10 of
0:str2:=str2+chr(48);
1:str2:=str2+chr(49);
2:str2:=str2+chr(50);
3:str2:=str2+chr(51);
4:str2:=str2+chr(52);
5:str2:=str2+chr(53);
6:str2:=str2+chr(54);
7:str2:=str2+chr(55);
8:str2:=str2+chr(56);
9:str2:=str2+chr(57);
end;
a:=a div 10;
end;
l2:=length(str2);
for j:=l2 downto 1 do str:=str+str2[j];
str:=str+' ';
tf:=false;
continue;
end;
str:=str+str1[i]+' ';
continue;
end
else
begin
a:=a*10+(ord(str1[i])-48);
tf:=true;
continue;
end;
end;
'(':begin p:=p+1;s[p]:='('; end;
')':begin
while s[p]<>'(' do
begin
str:=str+s[p]+' ';p:=p-1;
end;
p:=p-1;
end;
'+','-':begin
while (s[p]<>'(') and (p<>0) do
begin str:=str+s[p]+' ';p:=p-1;end;
p:=p+1;s[p]:=str1[i];
end;
'*','/':begin
while (p<>0) and ((s[p]='*') or (s[p]='/')) do
begin
str:=str+s[p]+' ';p:=p-1;
end;
p:=p+1; s[p]:=str1[i];
end;
end;
end;
while p<>0 do
begin
str:=str+s[p];p:=p-1;
end;
writeln(str);
l:=length(str);
tf:=false;
j:=1;
for i:=1 to l do
begin
if (str[i]=' ') or (i=1) then
begin
j:=i+1;
while str[j]<>' ' do inc(j);
end;
if str[i]=' ' then continue;
if j>1 then dec(j);
str1:='';
if ((j-i)=0) and (str[i]>='0') and (str[i]<='9') then
begin
inc(t);
val(str[i],b[t],k2);
end;
if ((j-i)>0) and (str[i]>='0') and (str[i]<='9') then
begin
for k:=i to j do str1:=str1+str[k];
inc(t);
val(str1,b[t],k2);
j:=i;
end;
case str[i] of
'+':begin b[t-1]:=b[t-1]+b[t];dec(t); end;
'-':begin b[t-1]:=b[t-1]-b[t];dec(t); end;
'*':begin b[t-1]:=b[t-1]*b[t];dec(t); end;
'/':begin b[t-1]:=b[t-1]/b[t];dec(t); end;
end;
end;
if (b[1]-round(b[1]))=0 then writeln(round(b[1]))
else writeln(b[1]);
end.

3,423

社区成员

发帖
与我相关
我的任务
社区描述
其他开发语言 其他开发语言
社区管理员
  • 其他开发语言社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧