表达式求值(中缀)

Posted brilliant107

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了表达式求值(中缀)相关的知识,希望对你有一定的参考价值。

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

 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.

 

以上是关于表达式求值(中缀)的主要内容,如果未能解决你的问题,请参考以下文章

中缀表达式求值的方法—栈

中缀表达式转换成后缀表达式并求值

全网最高端?中缀表达式转为后缀表达式以及求值(可用于负数,阶乘)

中缀表达式求值

中缀表达式转为后缀表达式(逆波兰式)求值

中缀表达式转为后缀表达式(逆波兰式)求值