一个数字的圆整问题:设定x是一个正实数。
(1)x>=10时,x圆整到最接近的整数值;
eg:12.63→13;    12.48→12
(2)x>5 and x<10时,x圆整到最接近的尾数为0.5μm的小数或整数;
eg:8.76→9;      8.33→8.5;      8.18→8 
(3)x<=5时,x圆整到最接近的相差小于0.1的一位小数或整数。
eg:3.96→4;      3.86→3.9;      3.01→3
要求:自定义一个函数。请高手指点一下!

解决方案 »

  1.   


    function MyRound(X:real):real;
    begin
        if X>10 then
            Result:=Round(X)
        else if x>5 then
            Result:=Round(Round(2*X)/2*10) /10
        else
            Result:=Round(X*10)/10;
    end;
      

  2.   

    什么样的误差?举个例子说下。这个函数返回本身就是不对的,因为即使是返回了3.9,可能也因为浮点数表达的问题,而不是3.9,是3.8999999或3.900001等。
    只有function Myround(X:real):string;这样定义的函数处理才可能是正确的结果。
      

  3.   

    function MyRound(X:real):real;
    begin
        if X>=10 then
            Result:=Round(X)
        else if X>5 then
            Result:=Round(X*2)/2
        else if X>0 then
            Result:=Round(X*10)/10
        else
            Result:=0;
    end;
      

  4.   

    function GetMyFloat(aFloat:double):double;
    var
      tmpResult:double;
      aDouble,aSubDouble:double;
      iInt:integer;
    //取小数部分
    function GetFloat(aMyFloat:double):double;
    var
      sFloat:string;
      aResult:double;
    begin
      sFloat:=floattostr(aMyFloat);
      if pos('.',sFloat)>0 then
        aResult:=strtofloat('0.'+copy(sFloat,pos('.',sFloat)+1,length(sFloat)-pos('.',sFloat)))
      else
        aResult:=0;
      result:=aResult;
    end;
    //取整数部分
    function GetInt(aMyFloat:double):integer;
    var
      sFloat:string;
      aResult:integer;
    begin
      sFloat:=floattostr(aMyFloat);
      if pos('.',sFloat)>0 then
        aResult:=strtoint(copy(sFloat,1,pos('.',sFloat)-1))
      else
        aResult:=0;
      result:=aResult;
    end;
    //主函数
    begin
      if aFloat>=10 then
        tmpResult:=strtoint(format('%.0f',[aFloat]))
      else if (aFloat>5) and (aFloat<10) then
      begin
        aDouble:=GetFloat(aFloat);
        iInt:=GetInt(aFloat);
        if aDouble >=0.5 then
        begin
          aSubDouble:=aDouble-0.5;
          if aSubDouble>=0.25 then
            tmpResult:=iInt+1.0
          else
            tmpResult:=iInt+0.5;
        end
        else
        begin
          if aDouble>=0.25 then
            tmpResult:=iInt+0.5
          else
            tmpResult:=iInt;
        end;
      end
      else if aFloat<=5 then
      begin
        tmpResult:=strtofloat(format('%.1f',[aFloat]));
      end;
      
      result:=tmpResult;
    end;//测试在一个窗体上放 两个Edit和一个Button
    procedure TForm1.btn1Click(Sender: TObject);
    begin
      edt2.Text:=floattostr(GetMyFloat(strtofloat(edt1.Text)));
    end;