码迷,mamicode.com
首页 > 其他好文 > 详细

表达式求值(中缀)

时间:2018-08-02 22:56:12      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:trunc   fun   代码   bsp   cti   run   down   ble   str   

题解。。。未完待续,先上代码

 1 var
 2 s:ansistring;
 3 i,t:longint;
 4 c:array[0..10000]of longint;
 5 function pow(x,y:double):double;
 6  var i:longint; k:double;
 7  begin
 8   k:=1;
 9   for i:=1 to trunc(y) do
10    begin
11     k:=k*x;
12    end;
13    exit(k);
14  end;
15  
16 function num(l,r:longint):double;
17  var sum,w:double; i:longint; dian:boolean;
18  begin
19  sum:=0;w:=1; dian:=false;
20   for i:=l to r do
21    begin
22     if (s[i]>=0)and(s[i]<=9) then
23      begin sum:=sum*10+ord(s[i])-48;
24            if dian then w:=w*10;
25      end;
26      if s[i]=.  then dian:=true;
27    end;
28    exit(sum / w);
29  end;
30  function oper(x:longint):boolean;
31   begin
32    if (s[x]=+)or(s[x]=-)or(s[x]=*)or(s[x]=/)or(s[x]=^) then
33    exit(true);
34    exit(false);
35   end;
36 function dfs(l,r,d:longint):double;
37  var bj:boolean; i:longint;
38  begin
39  if l>r then exit;
40   bj:=false;
41  // writeln(dfs:0:2);
42    for i:=l to r do
43     begin
44      if oper(i) then begin bj:=true;break;end;
45     end;
46     if not bj then exit(num(l,r));
47     for i:=r downto l do
48      begin
49        if (not oper(i))or(c[i]<>d) then continue;
50        if s[i]=+ then exit(dfs(l,i-1,d)+dfs(i+1,r,d));
51        if s[i]=- then exit(dfs(l,i-1,d)-dfs(i+1,r,d));
52      end;
53     for i:=r downto l do
54      begin
55       if (not oper(i))or(c[i]<>d) then continue;
56       if s[i]=* then exit(dfs(l,i-1,d)*dfs(i+1,r,d));
57       if s[i]=/ then exit(dfs(l,i-1,d)/dfs(i+1,r,d));
58      end;
59      for i:=r downto l do
60       begin
61        if (not oper(i))or(c[i]<>d) then continue;
62        if s[i]=^ then exit(pow(dfs(l,i-1,d),dfs(i+1,r,d)));
63       end;
64      exit(dfs(l,r,d+1));
65  end;
66 begin
67  readln(s);
68  inc(t);
69  for i:=1 to length(s)  do
70   begin
71     if s[i]=( then inc(t);
72     if s[i]=)then dec(t);
73     c[i]:=t;
74   end;
75   writeln(dfs(1,length(s),1):0:2);
76 end.

 

表达式求值(中缀)

标签:trunc   fun   代码   bsp   cti   run   down   ble   str   

原文地址:https://www.cnblogs.com/brilliant107/p/9409671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!