[Delphi]執行字串運算式(參考 http://www.swissdelphicenter.ch/torry/showcode.php?id=470 )
1: procedure TForm1.btn1Click(Sender: TObject);
2: function Calculate(SMyExpression: string; digits: Byte): string;
3: // Calculate a simple expression
4: // Supported are: Real Numbers, parenthesis
5: var
6: z: Char;
7: ipos: Integer;
8:
9: function StrToReal(chaine: string): Real;
10: var
11: r: Real;
12: Pos: Integer;
13: begin
14: Val(chaine, r, Pos);
15: if Pos > 0 then Val(Copy(chaine, 1, Pos - 1), r, Pos);
16: Result := r;
17: end;
18:
19: function RealToStr(inreal: Extended; digits: Byte): string;
20: var
21: S: string;
22: begin
23: Str(inreal: 0: digits, S);
24: realToStr := S;
25: end;
26:
27: procedure NextChar;
28: var
29: s: string;
30: begin
31: if ipos > Length(SMyExpression) then
32: begin
33: z := #9;
34: Exit;
35: end
36: else
37: begin
38: s := Copy(SMyExpression, ipos, 1);
39: z := s[1];
40: Inc(ipos);
41: end;
42: if z = ' ' then nextchar;
43: end;
44:
45: function Expression: Real;
46: var
47: w: Real;
48:
49: function Factor: Real;
50: var
51: ws: string;
52: begin
53: Nextchar;
54: if z in ['0'..'9'] then
55: begin
56: ws := '';
57: repeat
58: ws := ws + z;
59: nextchar
60: until not (z in ['0'..'9', '.']);
61: Factor := StrToReal(ws);
62: end
63: else if z = '(' then
64: begin
65: Factor := Expression;
66: nextchar
67: end
68: else if z = '+' then Factor := +Factor
69: else if Z = '-' then Factor := -Factor;
70: end;
71:
72: function Term: Real;
73: var
74: W: Real;
75: begin
76: W := Factor;
77: while Z in ['*', '/'] do
78: if z = '*' then w := w * Factor
79: else
80: w := w / Factor;
81: Term := w;
82: end;
83: begin
84: w := term;
85: while z in ['+', '-'] do
86: if z = '+' then w := w + term
87: else
88: w := w - term;
89: Expression := w;
90: end;
91: begin
92: ipos := 1;
93: Result := RealToStr(Expression, digits);
94: end;
95: begin
96: ShowMessage(edt1.Text + ' = ' + Calculate(edt1.Text, 3));//測試
97: end;