急急急!!!大家知道 怎样让从 键盘获取的 “算式“计算出来吗? (100分)

K

konnekt

Unregistered / Unconfirmed
GUEST, unregistred user!
就跟 文曲星一样 ,输入的数学式子 如 (1+1)*2
提交给程序后 程序可以把该 字符串识别为 数学算式,而不是 字符串,
经过处理之后 就可以把它 的答案算出来呢??~
 
你可以编写一个转换计算程序,在本论坛查找可以找到现成的计数器程序。也有控件
可以实现表达式解释。
 
我有一个表达式解析的程序
 
这个属于编译原理,建议看看编译原理的书
 
ZsWang
//完整代码
uses
Math;
procedure Bracket(mText: string;
var nLStr, nCStr, nRStr: string);
var
L, R: Integer;
I: Integer;
B: Boolean;
begin
nLStr := '';
nCStr := '';
nRStr := '';
B := True;
L := 0;
R := 0;
for I := 1 to Length(mText)do
if B then
begin
if mText = '(' then
Inc(L)
else
if mText = ')' then
Inc(R);
if L = 0 then
nLStr := nLStr + mText
else
if L > R then
nCStr := nCStr + mText
else
B := False;
end else
nRStr := nRStr + mText;
Delete(nCStr, 1, 1);
end;
{ Bracket }
function Calc(mText: string): string;
var
vText: string;
function fCalc(mText: string): string;
var
vLStr, vCStr, vRStr: string;
I, J, K, L: Integer;
begin
L := Length(mText);
if Pos('(', mText) > 0 then
begin
Bracket(mText, vLStr, vCStr, vRStr);
Result := fCalc(vLStr + fCalc(vCStr) + vRStr);
// ~
end else
if (Pos('+', mText) > 0) or (Pos('-', mText) > 0) then
begin
I := Pos('+', mText);
J := Pos('-', mText);
if I = 0 then
I := L;
if J = 0 then
J := L;
K := Min(I, J);
vLStr := Copy(mText, 1, Pred(K));
vRStr := Copy(mText, Succ(K), L);
if vLStr = '' then
vLStr := '0';
if vRStr = '' then
vRStr := '0';
if I = K then
Result := FloatToStr(StrToFloat(fCalc(vLStr)) + StrToFloat(fCalc(vRStr)))
else
Result := FloatToStr(StrToFloat(fCalc(vLStr)) - StrToFloat(fCalc(vRStr)))
end else
if (Pos('*', mText) > 0) or (Pos('/', mText) > 0) then
begin
I := Pos('*', mText);
J := Pos('/', mText);
if I = 0 then
I := L;
if J = 0 then
J := L;
K := Min(I, J);
vLStr := Copy(mText, 1, Pred(K));
vRStr := Copy(mText, Succ(K), L);
if vLStr = '' then
vLStr := '0';
if vRStr = '' then
vRStr := '0';
if I = K then
Result := FloatToStr(StrToFloat(fCalc(vLStr)) * StrToFloat(fCalc(vRStr)))
else
Result := FloatToStr(StrToFloat(fCalc(vLStr)) / StrToFloat(fCalc(vRStr)))
end else
if Pos('_', mText) = 1 then
Result := FloatToStr(-StrToFloat(fCalc(Copy(mText, 2, L))))
else
Result := FloatToStr(StrToFloat(mText));
end;
var
I, L: Integer;
begin
vText := '';
L := Length(mText);
for I := 1 to Ldo
if (mText = '-') and (I < L) and (not (mText[Succ(I)] in ['+', '-', '(', ')'])) then
if (I = 1) or ((I > 1) and (mText[Pred(I)] in ['*', '/'])) then
vText := vText + '_'
else
if ((I > 1) and (mText[Pred(I)] in ['+', '-'])) or
((I > 1) and (mText[Pred(I)] = ')') and (I < L) and
(not (mText[Succ(I)] in ['+', '-', '(', ')']))) then
vText := vText + '+_'
else
vText := vText + mText
else
vText := vText + mText;
Result := fCalc(vText);
end;
{ Calc }
 
网上有现成的控件,自己找吧,很容易找到!
 
不要那么麻烦吧,发一条SQL语句不就行了
 
thank you all!
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
977
SUNSTONE的Delphi笔记
S
S
回复
0
查看
799
SUNSTONE的Delphi笔记
S
顶部