You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi开发带< >特殊符号数值计算器时字符串匹配报错问题

问题原因

你代码中的错误主要分为以下几类:

  • 函数使用错误:
    • ContainsText 仅支持检查单个子串是否存在,不支持直接传入字符串数组作为匹配项,传入数组会直接触发语法或运行错误
    • IndexStr 是全量匹配函数,会拿你输入的整个strEnteredResult和数组里的字符串做完全相等匹配,不是查找子串,所以不可能匹配到带数字的输入内容
  • 逻辑错误:
    • 变量intIndexCounter未赋值就直接在case语句中使用,取值是随机的,分支逻辑完全不可控
    • 找到符号后直接把strProcessedNumber覆盖为符号值,后续运算时调用StrToFloat(strProcessedNumber)会因为无法转换符号为数字直接报错
    • 提取数值时没有去掉strEnteredResult里的</>符号,直接调用StrToFloat转换带符号的字符串也会报错
    • boolLess、boolGreater未初始化,未匹配到符号的场景下可能出现随机值

修正后完整代码

type TMaths  =  (addition,subtraction,multiplication,division);

function fnc_ProcessNumber(strEnteredResult,strProcessedNumber:string;Math:TMaths) : string;
const 
  lessThan : string = '<';
  greaterThan : string = '>';
var
  intIndexMath:Integer;
  extNewResult, extProcessNum:Extended;
  boolLess,boolGreater:Boolean;
  strPureNum: string;
begin
  // 初始化变量
  boolLess := False;
  boolGreater := False;
  strPureNum := strEnteredResult;

  // 检查小于号
  intIndexMath := AnsiPos(lessThan, strEnteredResult);
  if intIndexMath > 0 then
  begin
    boolLess := True;
    // 提取纯数字部分,去掉符号
    Delete(strPureNum, intIndexMath, 1);
  end
  // 检查大于号(默认两种符号不会同时存在)
  else
  begin
    intIndexMath := AnsiPos(greaterThan, strEnteredResult);
    if intIndexMath > 0 then
    begin
      boolGreater := True;
      Delete(strPureNum, intIndexMath, 1);
    end;
  end;

  // 转换数字,异常处理避免非法输入崩溃
  try
    extNewResult := StrToFloat(strPureNum);
    extProcessNum := StrToFloat(strProcessedNumber);
  except
    Result := 'null';
    Exit;
  end;

  // 执行运算
  case Math of
    addition:
      extNewResult := extNewResult + extProcessNum;
    subtraction:
      extNewResult := Abs(extNewResult - extProcessNum);
    multiplication:
      extNewResult := extNewResult * extProcessNum;
    division:
      begin
        if extProcessNum = 0 then
        begin
          Result := 'null';
          Exit;
        end;
        extNewResult := extNewResult / extProcessNum;
      end;
  end;

  // 拼接结果和符号
  Result := FloatToStr(extNewResult);
  if boolLess then 
    Result := lessThan + Result
  else if boolGreater then 
    Result := Result + greaterThan;
end;

调用测试

调用fnc_ProcessNumber('0.320>','100',multiplication)即可得到运算结果32>,如果需要输出320>只需将第二个参数改为1000即可。

内容的提问来源于stack exchange,提问作者yokbi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:54:01