捐赠 | 广告 | 注册 | 发布 | 上传 | 关于我们    
  沪ICP备05001939号 DELPHI盒子 | 盒子论坛 | 盒子文章 | 盒子问答悬赏 | 最新更新 | 论坛检索 | 下载中心 | 高级搜索    
  精品专区 | 繁體中文 | 奖励公告栏 | 直通车账号登陆 | 关闭GOOGLE广告 | 临时留言    
 
广告
评论:Delphi表达式计算演示2
xiaohongna 35132 2008/7/29 13:39:35
楼主  我早很以前也写过一个~~

支持  = - * /  多重() 省略 *号~~

而且就一个函数。 但有一个缺点就是不能扩展,就是扩展更高级的运算符很难。
我采用的递归算法,没有自己建立栈,所以代码不多。
function Calculator(var calstr: pchar): double;
  Function Getoperatenum:double;          //取操作数
  var
    temp:pchar;
  begin
    temp:=calstr;
    result:=0;
    if calstr^='(' then
      begin
        Result:=calculator(calstr);
        exit;
      end;
    while ((calstr^>='0')and(calstr^<='9'))or (calstr^='.') do
      inc(calstr);
    result:=strtofloat(copy(temp,0,calstr-temp));
  end;
  Function Getoperater:byte;          //运算类型
  begin
    if calstr^='(' then          //支持 n(n) 这种省去 * 的格式
       Result:=ord('*')
    else
      begin
        result:=ord(calstr^);
        inc(calstr);
      end;
  end;
var
  operateNum:Double;
begin
  operateNum:=0;
  result:=0;
  while calstr^='(' do
    inc(calstr);
  result:=Getoperatenum;
  while (calstr^<>#0) or (calstr^<>')') do
    begin
      case Getoperater of
        ord('+'):result:=result+calculator(calstr);
        ord('-'):result:=result-calculator(calstr);
        ord('*'):result:=result*Getoperatenum;
        ord('/'):
          begin
          operateNum:=Getoperatenum;
          if operateNum<>0 then
          result:=result/operateNum
          else
          begin
          showmessage('公式格式错误');
          abort;
          end;
          end
        else
          exit;
      end;
    end;
  if calstr=')' then inc(calstr);
end;

// 去年的链接 ,转眼又一年了   咳  
http://bbs.pfan.cn/post-246485.html
mxymxy 35026 2008/7/22 10:00:41
2.采用的并行式词法分析不完善,只能用一位正数,现正欲改善
mxymxy 35025 2008/7/22 9:57:21
致歉:
1.由于代码疏忽,括号无法正常使用,应改正为如下:
.........
9:begin
          case nc of
          '+':begin
          WriteStat('S4');
          ReadChar;
          st.Push(4);
          end;
          '-':begin
          WriteStat('S5');
          ReadChar;
          st.Push(5);
          end;
          '*':begin
          WriteStat('S6');
          ReadChar;
          st.Push(6);
          end;
          '/':begin
          WriteStat('S7');
          ReadChar;
          st.Push(7);
          end;
          '^':begin
          WriteStat('S8');
          ReadChar;
          st.Push(8);
          end;
          ')':begin
          WriteStat('S10');
          ReadChar;
          st.Push(10);
          end;
          else begin
          Error('There is a wrong char ('+ss.Pop+') behind ('+ss.Pop+') in front of ('+nc+')',cpErrorChar);
          Exit;
          end;
          end;
        end;//I9
.........
第一页 上一页 下一页 最后页 有 3 条纪录 共1页 1 - 3
 用户名:
 密 码:
自动登陆(30天有效)
 
  DELPHI盒子版权所有 1999-2023 V4.01 粤ICP备10103342号-1 更新RSS列表