其实不难,亲自动手编了一个,保证原创.下面说下思路:不管一个表达式多复杂,它的形式都是: A op B在这里,暂且把A称为左操数,B称为右操作数,op称为操作符关键就是找出op,然后左右一分,分成A与B两部分左操作数和右操作数具体又可能有N层嵌套,弄个递归就行了,不用多考虑.//下面是完整源码,可直接运行,测试正确//我这里只考虑小括号,与+-*/四种运算符//再扩充一下,把每个运算编成一个函数,那谅更灵活了...unit Unit1;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;type TForm1 = class(TForm) Edit1: TEdit
//表达式,如: 1-((1-X)/4) Edit2: TEdit
//变量值,如: 5 Edit3: TEdit
//计算结果 Label1: TLabel
Label2: TLabel
Label3: TLabel
Button1: TButton
procedure Button1Click(Sender: TObject)
private { Private declarations } function CalFunc(const ExpText: string): string
public { Public declarations } end;var Form1: TForm1;implementation{$R *.dfm} { TForm1 }procedure TForm1.Button1Click(Sender: TObject);var ExpText, X, sResult: string;begin ExpText:= Edit1.Text
X:= Edit2.Text
//中英文修正(防止那些粗心大意的人) ExpText:= StringReplace(ExpText, '+', '+', [rfReplaceAll, rfIgnoreCase])
ExpText:= StringReplace(ExpText, '-', '-', [rfReplaceAll, rfIgnoreCase])
ExpText:= StringReplace(ExpText, '*', '*', [rfReplaceAll, rfIgnoreCase])
ExpText:= StringReplace(ExpText, '/', '/', [rfReplaceAll, rfIgnoreCase])
ExpText:= StringReplace(ExpText, ' ', '', [rfReplaceAll, rfIgnoreCase])
ExpText:= StringReplace(ExpText, ' ', '', [rfReplaceAll, rfIgnoreCase])
//替换变量 ExpText:= StringReplace(ExpText, 'X', X, [rfReplaceAll, rfIgnoreCase])
//计算 sResult:= CalFunc(ExpText)
Edit3.Text:= sResult
if sResult = '' then ShowMessage('表达式错误');end;function TForm1.CalFunc(const ExpText: string): string;var i, Count: integer
S, S1, S2: string
v, v1, v2: Double;begin result:= ''
S:= ExpText
while (Length(S) > 1) and (S[1] = '(') and (S[Length(S)] = ')') do begin Delete(S, 1, 1)
Delete(S, Length(S), 1)
end
if TryStrToFloat(S, v) then begin result:= S
exit
end
S1:= ''
S2:= ''
Count:= 0
for i:= 1 to Length(S) do begin if S = '(' then inc(Count) else if S = ')' then dec(Count) else if S in ['+', '-', '*', '/'] then begin if Count = 0 then begin S1:= Copy(S, 1, i - 1)
S2:= Copy(S, i + 1, Length(S))
S1:= CalFunc(S1)
S2:= CalFunc(S2)
if TryStrToFloat(S1, v1) and TryStrToFloat(S2, v2) then begin if S = '+' then result:= FloatToStr(v1 + v2) else if S = '-' then result:= FloatToStr(v1 - v2) else if S = '*' then result:= FloatToStr(v1 * v2) else if S = '/' then result:= FloatToStr(v1 / v2)
end
exit
end
end
end;end;end.