得到四则混合运算的值(方法一)

 函数如下:

 

unit MyFunction;

interface

//得到四则混合运算的值  ,+-*/()的运算 20030307 by Judy @_@
//修改 maxN设置 表达式的最大输入字符
function GetExpressionValue(s:string):Double;

implementation

uses
  Windows, Messages, SysUtils, Classes,  Controls,  Dialogs,
  StdCtrls;

function GetExpressionValue(s: string): Double;
const
  maxN
=255;
var
  res,ch:char;
  oprTop,numTop:integer;
  opr:
array[1..maxN] of char;
  num:
array[1..maxN] of real;

  sTemp:string;


  
procedure error;
  
begin
    
//write(fout,'error!');
    showmessage(
'表达式错误,请检查!');
    Result :
=0;
    exit;
  
end;
  
function comp(a,b:char):char;
  
begin
    
if not(a in ['+','-','*','/','(',')','#']) or not(b in ['+','-','*','/','(',')','#']) then result:='e'
    
else
    
case a of
      
'+','-'case b of
                 
'*','/','(':result:='<';
                 
else result:='>';
               
end;
      
'*','/':if b='(' then result:='<' else result:='>';
      
'(':    if b=')' then result:='=' else if b='#' then result:='e' else result:='<';
      
')':    if b='(' then result:='e' else result:='>';
      
'#':    if b=')' then result:='e' else if b='#' then result:='R' else result:='<';
    
end;
  
end;
  
function cal(a,b:real;p:char):real;
  
begin
    
case p of
      
'+': result:=a+b;
      
'-': result:=a-b;
      
'*': result:=a*b;
      
'/'if b=0 then
           
begin
             error;

             ShowMessage(
'[B] - '+sTemp);

             result:
=0;
           
end
           
else result:=a/b;
    
end;
  
end;
  
function GetNumber(var s:string):real;
  
var
    i,code:integer;
  
begin
    i:
=1;
    
while (i<=length(s))and(s[i] in ['0'..'9','.']) do inc(i);
    val(copy(s,
1,i-1),result,code);
    delete(s,
1,i-1);
  
end;
begin
  sTemp :
= s;

  opr[
1]:='#';
  s:
=s+'#';
  oprTop:
=1;
  numTop:
=0;
  res:
=' ';
  
repeat
  
if s[1in ['0'..'9'then
    
begin
     inc(numTop);
     num[numTop]:
=GetNumber(s);
    
end
   
else
    
begin
     ch:
=s[1];
     delete(s,
1,1);
     
repeat
     res:
=comp(opr[oprTop],ch);
     
case res of
     
'>':begin
           num[numTop
-1]:=cal(num[numTop-1],num[numtop],opr[oprTop]);
           dec(numTop);
           dec(oprTop);
         
end;
     
'<':begin
           inc(oprTop);
           opr[oprTop]:
=ch;
         
end;
     
'=':begin
           dec(oprTop);
         
end;
     
'e':begin
           error;
           ShowMessage(
'[A] - '+sTemp);
           result:
=0;
           exit;
         
end;
     
'R':begin
           result:
=num[numTop];
         
end;
     
end;
     
until res<>'>';
    
end;
  
until res='R';
end;

end.
posted @ 2008-08-05 11:45  威尼斯的夏天  阅读(249)  评论(0编辑  收藏  举报