题解:利用递归来做。因为有括号要先算出来,所以你需要设定一个优先级,在递归的时候每次先找优先级最小的,但是这说起来很抽象,
你可以把它看做右图中的一样,每遇到一个‘’(‘’ 就把优先级加1,遇到‘’)‘’就把优先级减1,对于每个s[i]都记录它的优先级。然后就可以递归了,
遇到运算符就先递归处理优先级小的,然后你要从后往前搜,因为递归的部分是先算的!它是由小推到大,小范围的先算
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.