哪个数字更接近

时间:2013-04-30 08:39:18

标签: delphi

我怎样才能找出哪个数字更接近?说我的值是“1”,我有两个var,A:= 1.6和b:= 1.001

目前正在查看一些数字并采用0.1%+/-差异和+/- 0.6差异..我只需要看看哪个答案更接近起始值..代码到目前为止..

也没什么大不了的,代码只是阻止我手动完成所有操作:D

    procedure TForm1.Button1Click(Sender: TObject);
var
winlimit,test6high,test6low,test6,test1high,test1low,test1,value: double;
begin
 value := 1.0;
 while value < 1048567 do
  begin
     test6high := value + 0.6 ;
     test6low := value - 0.6 ;

     test1high := (-0.1 * value)/100;
     test1high := value - test1high;

     test1low := (0.1 * value)/100;
     test1low := value - test1low;

     memo1.Lines.Add('value is '+floattostr(value)+': 1% High:'+floattostr(Test1high)+' 1% Low:'+floattostr(Test1low));
     memo1.Lines.Add('value is '+floattostr(value)+': 0.6 +/- '+floattostr(Test6high)+' 0.6 Low:'+floattostr(Test6low));
     memo1.Lines.Add(' ');
     value := value*2;
 end
end;

1 个答案:

答案 0 :(得分:4)

我认为你的意思是这样的功能:

function ClosestTo(const Target, Value1, Value2: Double): Double;
begin
  if abs(Target-Value1)<abs(Target-Value2) then
    Result := Value1
  else
    Result := Value2;
end;

如果您使用IfThen单元中的Math,则可以更简洁地编写它:

function ClosestTo(const Target, Value1, Value2: Double): Double;
begin
  Result := IfThen(abs(Target-Value1)<abs(Target-Value2), Value1, Value2);
end;
相关问题